我想在一个对象数组上实现自定义过滤器。
let obj = [{
flag: true
note: "asdasd"
id: "we"
name: "tt1"
list: [{
"id" : 1,
"detail" : "asdasda"
},
{
"id" : 2,
"detail" : "asdasda"
}]
},
{
flag: false
note: "asdasd"
id: "we"
name: "tt1"
list: [{
"id" : 1,
"detail" : "asdasda"
},
{
"id" : 2,
"detail" : "asdasda"
}]
}
]
当用户搜索id = 1时,我希望像
那样输出[{
flag: true
note: "asdasd"
id: "we"
name: "tt1"
list: [{
"id" : 1,
"detail" : "asdasda"
}]
}]
搜索将首先在标志上执行=== true然后在id上为标志为true的那些对象执行。
我的管道代码如下
@Pipe({ 名称:'管道' })
export class PipeNew implements PipeTransform {
transform(value: any, search: any): any {
let filteredArray = value
.filter((element) => {
if (element.flag)
return element ;
})
.filter((element) =>
element.list.some(listObj => (listObj.id.indexOf(search) > -1)))
.map((element) => {
let newElt = Object.assign({}, element);
return newElt.list.filter(obj => (obj.id.indexOf(search) > -1))
});
return filteredArray;
}
}
但我只是得到了如下的输出
[{
"id" : 1,
"detail" : "asdasda"
}]
预期
[{
flag: true
note: "asdasd"
id: "we"
name: "tt1"
list: [{
"id" : 1,
"detail" : "asdasda"
}]
}]
请帮助谢谢;)
答案 0 :(得分:0)
我相信您在映射之前已经在列表ID上过滤了结果,因此您不需要在返回的行上进行过滤。改变它
let filteredArray = value.filter((element) => {
if (element.flag){
return element.list.filter((item)=> {
return item.id.indexOf(search) > -1;
});
}
}).map((element) => {
let newElt = Object.assign({}, element);
return newElt;
});