gpt4 book ai didi

javascript - 通过匹配父项或子项中的关键字过滤嵌套数组

转载 作者:行者123 更新时间:2023-12-04 01:31:49 26 4
gpt4 key购买 nike

我需要通过匹配关键字来过滤嵌套数组。它必须返回与父级或其子级之一的 name 属性匹配的所有对象,并过滤其子级。

例子:

[
{
"name": "abc",
"children": [
{ "name": "abcd" },
{ "name": "efg" }
]
},
{
"name": "hjk",
"children": [
{ "name": "lmn" },
{ "name": "opq" }
]
},
{
"name": "xyz",
"children": [
{ "name": "lmn" },
{ "name": "abcdef" }
]
}
]

如果文本输入是“ab”,那么它必须返回:

[
{
"name": "abc",
"children": [
{ "name": "abcd" }
]
},
{
"name": "xyz",
"children": [
{ "name": "abcdef" }
]
}
]

(它匹配父级或至少一个子级,并返回但父级和子级)

目前,我只能像这样过滤 parent :

filteredArray = _.filter(array, (parent) => {
return _.includes(_.toLower(parent.name), _.toLower(filterText));
});

我怎样才能修改它以便它也过滤 child ?

编辑: parent 可以有空的或没有 child 的数组。

最佳答案

对于每个元素检查名称并过滤其子元素,如果其中一个为真,则将具有过滤子元素的元素推送到新数组

const data = [{"name": "abc", "children": [{ "name": "abcd" }, { "name": "efg" }  ] }, {"name": "hjk","children": [{ "name": "lmn"},  { "name": "opq" }  ]}, { "name": "xyz","children": [{ "name": "lmn"
},{"name": "abcdef" } ] }, {"name": "abc"}, {"name": "abc", children: []}];

const res = data.reduce((acc, a) => {
const ch = a.children && a.children.filter(b => b.name.includes('ab'));
if(ch && ch.length) acc.push({...a, children: ch});
else if(a.name.includes('ab')) acc.push({ name: a.name });
return acc;
}, []);

console.log(res);

关于javascript - 通过匹配父项或子项中的关键字过滤嵌套数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51513293/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com