gpt4 book ai didi

javascript - 如何在 typescript 中找到树中的树

转载 作者:行者123 更新时间:2023-12-01 01:32:03 25 4
gpt4 key购买 nike

假设我在 javascript 中有一棵树

a1 
--b
----c1
a2
--b2
--b3
----c2

如果我想找到c2,它应该返回a2->b3->c2

假设我的 json 看起来像这样?

treeFamily = {
name : "Parent",
children: [{
name : "Child1",
children: [{
name : "Grandchild1",
children: []
},{
name : "Grandchild2",
children: []
},{
name : "Grandchild3",
children: []
}]
}, {
name: "Child2",
children: []
}]
};

最佳答案

您可以检查嵌套的子级是否具有所需的键/值。然后获取name并将结果交给外部调用。

function findPath(array, target) {
var path;
array.some(({ name, children }) => {
var temp;
if (name === target) {
path = [name];
return true;
}
if (temp = findPath(children, target)) {
path = [name, ...temp];
return true;
}
});
return path;
}

var treeFamily = { name: "Parent", children: [{ name: "Child1", children: [{ name: "Grandchild1", children: [] }, { name: "Grandchild2", children: [] }, { name: "Grandchild3", children: [] }] }, { name: "Child2", children: [] }] };

console.log(findPath([treeFamily], 'Grandchild2'));
console.log(findPath([treeFamily], 'foo'));

关于javascript - 如何在 typescript 中找到树中的树,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53175946/

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