我有这样的json数据:
[
{
"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"
}
]我需要建立这样的输入字段过滤器,所以如果我输入'Android魅族‘,那么它应该找到’魅族‘项目。基本上,它应该做和这个插件一样的事情:http://plnkr.co/edit/kozaU39E74yqjZCpgDqM?p=preview,但我需要在一个输入字段中完成所有这些。
感谢您的帮助!
发布于 2017-07-13 02:17:29
这里的重点是,为了实现如何查找/过滤与输入匹配的对象的逻辑,无论是在不同的属性中还是在单个属性中,一旦您能够编写逻辑,创建角度过滤器就没有什么大不了的。
在这里,我编写了一个过滤器,假设你的对象具有扁平的结构。因为你想在对象中找到所有标记时进行过滤,比如"Android Meizu"将返回在某个字段中包含"Android",在某个字段中包含"Meizu",或者在某个字段中包含完整"Android Meizu"的对象,因此我们调用split,并检查如果所有标记都是对象任何值的超部分,我们就可以获取该对象,这样两个条件都可以完全满足。下面是一个可以正常工作的代码示例
.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;
}
})如果有什么不清楚的地方,请发表意见。
发布于 2017-07-13 00:09:46
下面是angular 2实现,其中IProduct[]是我的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 https://rahulcvng2.netlify.com/products上看到这一点。
https://stackoverflow.com/questions/45062426
复制相似问题