Javascript 多参数角输入滤波器
我有这样的json数据:Javascript 多参数角输入滤波器,javascript,angularjs,json,Javascript,Angularjs,Json,我有这样的json数据: [ { "id":1, "brand":"Apple", "model":"Iphone 5", "os":"macOs" }, { "id":2, "brand":"Apple", "model":"Iphone 6", "os":"macOs" }, { "
[
{
"id":1,
"brand":"Apple",
"model":"Iphone 5",
"os":"macOs"
},
{
"id":2,
"brand":"Apple",
"model":"Iphone 6",
"os":"macOs"
},
{
"id":3,
"brand":"Samsung",
"model":"Samsung Galaxy",
"os":"Android"
},
{
"id":4,
"brand":"Meizu",
"model":"Meizu M2 note",
"os":"Android"
}
]
我需要建立这样的输入域过滤器,所以如果我输入“安卓魅族”,那么它应该会找到“魅族”项。
基本上,它应该做和这个plunk差不多的事情:但我需要在一个输入字段中完成所有这些
谢谢你的帮助 这里是angular 2实现,其中IPProduct[]是我的json输入接口
import { Pipe, PipeTransform } from '@angular/core';
import { IProduct } from '../products/product';
@Pipe({
name:'productFilter'
})
export class ProductFilterPipe implements PipeTransform{
transform(value: IProduct[], filterBy: string): IProduct[] {
filterBy = filterBy ? filterBy.toLocaleLowerCase() : null;
return filterBy ? value.filter((product: IProduct) =>
product.productName.toLocaleLowerCase().indexOf(filterBy) !== -1) : value;
}
}
您可以在这个url上看到这一点
这里的要点是,要实现这样一种逻辑,即如何在不同属性或单个属性中查找/筛选出与输入匹配的对象,一旦您能够编写逻辑,创建角度过滤器就没有什么大不了的了 在这里,我编写了一个过滤器,假设您的对象具有平面结构。 由于您希望在对象中找到所有令牌时进行过滤,例如
“Android魅族”
将返回在某些字段中具有“Android”
的对象,以及在某些字段中具有“魅族”
的对象,或者在某些字段中具有整个“Android魅族”
的对象,我们将其拆分,并检查,如果所有标记都是该对象的任何值的sup部分,那么我们可以获取该对象,这样一来,两个条件都将满字段。下面是一个应该可以工作的代码示例
.filter('detailSearch', function() {
return function(input, filterStr) {
//this will split to strings by space, if space is not there
//still it will wrap in array the single element
//the filter will remove empty strings if multiple spaces are there
var tokens = filterStr.split(" ").filter(function(s) {
return s
});
var op = input.filter(function(obj) {
//taking valuesassuming your object having flat structure,
//if all not strings converted to string and lower case
var values = Object.values(obj).map(function(v) {
return v.toString().toLowerCase()
});
var keysExistsInObj = tokens.filter(function(key) {
return values.some(function(v) {
return v.includes(key.toLowerCase())
});
});
//checking for all tokens exists
return keysExistsInObj.length === tokens.length;
});
return op;
}
})
如果有任何不清楚的地方,请发表评论。这应该是您想要的吗
Android Meizu
将找到所有拥有Android
或Meizu
的项目,或者它将找到同时拥有这两种功能的项目?@KoushikChatterjee它应该找到所有拥有Android和Meizu的项目。@ManavalanMavan添加了一个答案。请查收。