gpt4 book ai didi

javascript - 在深层嵌套的对象数组中查找值,递归地,javascript

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

我有一个嵌套对象数组,具有父子关系:

  [  
{
"id":"5b9ce8d51dbb85944baddfa5",
"name":"EARBANG",
"parent_id":0,
"status":"Inactive",
"children":[
{
"id":"5b9ce8d5d978f75e4b1584ba",
"name":"DIGINETIC",
"parent_id":"5b9ce8d51dbb85944baddfa5",
"status":"Active",
"children":[
{
"id":"5b9ce8d5cb79d63c8b38018c",
"name":"PREMIANT",
"parent_id":"5b9ce8d5d978f75e4b1584ba",
"status":"Active",
}
]
}
]
},
{
"id":"5b9ce8d51650fac75fa359c8",
"name":"GEEKOLOGY",
"parent_id":0,
"status":"Active",
},
{
"id":"5b9ce8d59f52e801a2e40a97",
"name":"TOYLETRY",
"parent_id":0,
"status":"Inactive",
},
{
"id":"5b9ce8d5d136fcfed2f3e0dd",
"name":"PAPRIKUT",
"parent_id":0,
"status":"Inactive",
},
{
"id":"5b9ce8d53afb7a61e188c48e",
"name":"EYERIS",
"parent_id":0,
"status":"Inactive",
}
]

我要的是:

1- 查找具有 id 的对象,例如5b9ce8d51dbb85944baddfa5

2- 递归地迭代该对象的子数组(如果非空),并在数组中获取其所有子代、孙代和曾孙代的 ID。

所以我的结果会是这样

{
"id":"5b9ce8d51dbb85944baddfa5",
childs: ["5b9ce8d5d978f75e4b1584ba", "5b9ce8d5cb79d63c8b38018c", ...]
}

我尝试了一些可用的堆栈溢出解决方案,但无法使其工作。

如果有人能帮助我,我将不胜感激,我的 DS 不是那么强。

谢谢

最佳答案

这是一个搜索递归函数:

function searchRecursive(data, id) {
let found = data.find(d => d.id === id);
if (!found) {
let i = 0;
while(!found && i < data.length) {
if (data[i].children && data[i].children.length) {
found = searchRecursive(data[i].children, id);
}
i++;
}
}
return found;
}

关于javascript - 在深层嵌套的对象数组中查找值,递归地,javascript,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52453666/

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