gpt4 book ai didi

javascript - 按父 ID 递归搜索后代

转载 作者:行者123 更新时间:2023-11-30 19:36:59 24 4
gpt4 key购买 nike

我有平面阵列(展平树)。如何使用 Lodash 库通过 parentIds 实现对 child 的递归搜索?

例如,通过 id = 1 我需要获取“JavaScript”、“React”和“Vue”。

array: 
[{
id: 1,
name: 'Development',
parentIds: [],
},
{
id: 2,
name: 'JavaScript',
parentIds: [1]
},
{
id: 3,
name: 'React',
parentIds: [2]
},
{
id: 4,
name: "Vue",
parentIds: [2]
}]

最佳答案

    $(function () {
var array =
[{
id: 1,
name: 'Development',
parentIds: [],
},
{
id: 2,
name: 'JavaScript',
parentIds: [1]
},
{
id: 3,
name: 'React',
parentIds: [2]
},
{
id: 4,
name: "Vue",
parentIds: [2]
}]

var getId = function (arrayItems, id) {
if (arrayItems) {
for (var i in arrayItems) {
if (arrayItems[i].id == id) {
return arrayItems[i];
};
var found = getId(arrayItems[i].items, id);
if (found) return found;
}
}
};

var searchedItem = getId(array, 3);
alert(searchedItem.name);
});

关于javascript - 按父 ID 递归搜索后代,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55839046/

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