使用.filter()函数筛选嵌套数组

h7appiyu  于 2021-09-13  发布在  Java
关注(0)|答案(1)|浏览(296)

我有一个如下所示的数组:

const data = [
 {"total": 24,"items":[{"id":1,"name":"foo1", "items": [{"label": "TEST", "total": 50}, {"label": "TEST2", "total": 50}]}]},
{"total": 25,"items":[{"id":2,"name":"foo2", "items": [{"label": "FOO", "total": 60}, {"label": "ANOTHER2", "total": 50}]}]},
{"total": 26,"items":[{"id":3,"name":"foo3", "items": [{"label": "BAR", "total": 70}, {"label": "LAST2", "total": 50}]}]},
];

我想在angular中使用.filter()函数,因此当我传入字符串“2”时,它返回的对象仅包含包含字符串“2”的嵌套数组,换句话说,应该返回以下内容:

[
 {"total": 24,"items":[{"id":1,"name":"foo1", "items": [{"label": "TEST2", "total": 50}]}]},
{"total": 25,"items":[{"id":2,"name":"foo2", "items": [{"label": "ANOTHER2", "total": 50}]}]},
{"total": 26,"items":[{"id":3,"name":"foo3", "items": [{"label": "LAST2", "total": 50}]}]},
];

我试过了

let values = data.items.filter(d => d.items.forEach(c => c.label.toLowerCase().includes(searchText.toLowerCase())
}))

它只返回一个空数组,
我也试过了

let values = data.items.forEach(d => d.items.filter(c => c.label.toLowerCase().includes(searchText.toLowerCase())
}))

let values = data.items.filter(d => d.items.every(c => c.label.toLowerCase().includes(searchText.toLowerCase())
}))

并且都返回未定义的数组和空数组。
正确的方法是什么?

72qzrwbm

72qzrwbm1#

const data = [
 {"total": 24,"items":[{"id":1,"name":"foo1", "items": [{"label": "TEST", "total": 50}, {"label": "TEST2", "total": 50}]}]},
{"total": 25,"items":[{"id":2,"name":"foo2", "items": [{"label": "FOO", "total": 60}, {"label": "ANOTHER2", "total": 50}]}]},
{"total": 26,"items":[{"id":3,"name":"foo3", "items": [{"label": "BAR", "total": 70}, {"label": "LAST2", "total": 50}]}]},
];

let searchText='TEST'

let values =  JSON.parse(JSON.stringify(data)).map(d => {
d.items.map(i=> {
i.items = i.items.filter(c =>c.label.toLowerCase().includes(searchText.toLowerCase()));
return i;
})
return d;
})

console.log(values)
let values =  JSON.parse(JSON.stringify(data)).map(d => {
d.items.map(i=> {
i.items = i.items.filter(c =>c.label.toLowerCase().includes(searchText.toLowerCase()));
return i;
})
return d;
})
``` `forEach` 不返回任何内容, `map` 返回数组,其中每个元素都由传递给它的函数的返回值替换。此外,由于目标数组位于数据[0]。项[0]。例如,项。我可能遗漏了括号或括号

相关问题