如何递归拿到树形结构数组内符合条件的数据
结构类似这样:
list:[
{
id:1,
},
{
id:2,
children:[
{
id:21,
name:'cc',
children:[
{
id:221,
name:'pp'
}
]
},
{
id:22,
name:'dd'
}
]
},
{
id:3,
children:[
{
id:31,
name:'ff'
},
{
id:32,
name:'ee'
}
]
},
]
就是多层嵌套的,子级是children。
我需要的是我拿到某一层的id,通过这个id递归这个数组拿到对应id的children数组返回给我。
比如我拿到了一个21,那么我需要拿到这里id为21的这个对象中的children数组。这个要如何拿
基于new bing部分指引作答:
您可以使用递归的方式来拿到指定id的children数组。以下是一个示例的JavaScript代码:
function findChildrenById(arr, id) {
for (let i = 0; i < arr.length; i++) {
if (arr[i].id === id) {
return arr[i].children || [];
}
if (Array.isArray(arr[i].children)) {
const result = findChildrenById(arr[i].children, id);
if (result.length > 0) {
return result;
}
}
}
return [];
}
const data = [
{
id: 1,
},
{
id: 2,
children: [
{
id: 21,
name: 'cc',
children: [
{
id: 221,
name: 'pp'
}
]
},
{
id: 22,
name: 'dd'
}
]
},
{
id: 3,
children: [
{
id: 31,
name: 'ff'
},
{
id: 32,
name: 'ee'
}
]
},
];
const id = 21;
const result = findChildrenById(data, id);
console.log(result);
在上述代码中,findChildrenById
函数通过遍历数组进行查找,如果找到具有指定id的对象,则返回其对应的children数组。如果该对象下还有children属性,那么会继续递归调用 findChildrenById
函数进行查找。最终,通过调用 findChildrenById(data, id)
来获取id为21的对象的children数组。
请注意,这只是一个简单的示例实现,您可以根据实际需求进行调整和扩展。
树形结构就使用递归,数组结构就使用find遍历查找
function getParentNode(tree, id) {
for (let i = 0; i < tree.length; i++) {
if (tree[i].children?.length) {
let result = tree[i].children.find((item) => item.id == id)
if (result) {
return result.children;
} else {
getParentNode(tree[i].children, id);
}
}
}
return null;
}