gpt4 book ai didi

javascript - 在具有完整路径的树中查找匹配节点

转载 作者:太空宇宙 更新时间:2023-11-04 16:27:38 24 4
gpt4 key购买 nike

我有一个像这样的对象数组

[{
name: "Peter",
children: [{
name: "John",
children: [{
name: "Joseph",
children: []
}]
}, {
name: "Shawn",
children: [{
name: "Joseph",
children: []
}]
}]
}, {
name: "Carl",
children: [{
name: "Sam",
children: [{
name: "JohnXX",
children: []
}]
}]
}]

每个人可以有多个 child ,每个 child 可以有任意数量的 child ,依此类推。

我想保留具有匹配子项的完整路径并排除不匹配子项。例如,如果我搜索 John 输出应该是这样的

[{
name: "Peter",
children: [{
name: "John",
children: [{
name: "Joseph",
children: []
}]
}]
}, {
name: "Carl",
children: [{
name: "Sam",
children: [{
name: "JohnXX",
children: []
}]
}]
}]

最佳答案

您需要生成一个仅包含相关部分的新对象。

该提案对于单个级别进行迭代,对于子级进行递归。

function getNodes(array, cb) {
return array.reduce(function iter(r, a) {
var children;
if (cb(a)) {
return r.concat(a);
}
if (Array.isArray(a.children)) {
children = a.children.reduce(iter, []);
}
if (children.length) {
return r.concat({ name: a.name, children: children });
}
return r;
}, []);
}

var data = [{ name: "Peter", children: [{ name: "John", children: [{ name: "Joseph", children: [] }] }, { name: "Shawn", children: [{ name: "Joseph", children: [] }] }] }, { name: "Carl", children: [{ name: "Sam", children: [{ name: "JohnXX", children: [] }] }] }];

console.log(getNodes(data, function (o) { return o.name.indexOf('John') !== -1; }));
.as-console-wrapper { max-height: 100% !important; top: 0; }

关于javascript - 在具有完整路径的树中查找匹配节点,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40095483/

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