我有一个数组[{id:1,label:"刘坤",children:[{id:2,lable:"刘坤2",children:[{id:3,label:"刘坤3"]}]}},{id:4,label:"刘坤4",children:[{}]}]。我现在知道id为3,如何获取我的所有父元素的id
时间: 2024-04-23 20:28:01 浏览: 19
您可以使用递归遍历的方式,在给定的数组中查找具有指定`id`的节点,并记录其所有父节点的`id`,最后返回一个包含父节点`id`的数组。
以下是一个示例代码:
```javascript
function getParentIds(data, targetId, parentIds = []) {
for (const node of data) {
if (node.id === targetId) {
return [...parentIds]; // 返回父节点的id数组(不包含自身)
}
if (node.children && node.children.length > 0) {
parentIds.push(node.id);
const result = getParentIds(node.children, targetId, parentIds);
if (result) {
return result;
}
parentIds.pop();
}
}
return null; // 没有找到指定id的节点
}
const data = [
{ id: 1, label: "刘坤", children: [{ id: 2, label: "刘坤2", children: [{ id: 3, label: "刘坤3" }] }] },
{ id: 4, label: "刘坤4", children: [{}] }
];
const targetId = 3;
const parentIds = getParentIds(data, targetId);
console.log(parentIds); // 包含指定id的所有父元素的id数组
```
在上述代码中,`getParentIds`函数接收数组`data`、目标`id`和父节点`id`数组`parentIds`作为参数。通过递归遍历数组中的节点,查找具有指定`id`的节点,并记录所有父节点的`id`,最后返回一个包含父节点`id`的数组。您可以调用`getParentIds`函数来获取指定`id`的所有父元素的`id`,并将结果打印到控制台或进行其他操作。
相关推荐
![doc](https://img-home.csdnimg.cn/images/20210720083327.png)
![doc](https://img-home.csdnimg.cn/images/20210720083327.png)
![7z](https://img-home.csdnimg.cn/images/20210720083312.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![.pdf](https://img-home.csdnimg.cn/images/20210720083646.png)
![doc](https://img-home.csdnimg.cn/images/20210720083327.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)