js递归遍历树形结构数据,获取所有数组id集合

您所在的位置:网站首页 js树结构递归 js递归遍历树形结构数据,获取所有数组id集合

js递归遍历树形结构数据,获取所有数组id集合

2023-11-06 01:31| 来源: 网络整理| 查看: 265

实现思路

可以使用递归遍历整个树形数组,将每个节点的id加入到一个数组中,最后返回这个数组即可。

数据准备 let datas = [ { id: "1", pId: "0", children: [ { id: "1-1", pId: "1", }, ], }, { id: "2", pId: "0", children: [ { id: "2-1", pId: "1", children: [ { id: "2-1-2", pId: "2", }, ], }, ], }, ]; 代码实现

方式一

function getAllIds(tree, result) { //遍历树 获取id数组 for (const i in tree) { result.push(tree[i].id); // 遍历项目满足条件后的操作 if (tree[i].children) { //存在子节点就递归 getAllIds(tree[i].children, result); } } return result; } 获取结果 console.log(getAllIds(datas, []), "getAllIds+++++++++");

方式二

function getAllIds(tree) { let result = []; if (!Array.isArray(tree)) { return result; } tree.forEach((node) => { result.push(node.id); if (Array.isArray(node.children)) { // result.push(...getAllIds(node.children)); result = result.concat(getAllIds(node.children)); } }); return result; } 获取结果 console.log(getAllIds(datas), "getAllIds+++++++++");

方式三

function getAllIds(tree, result) { if (!Array.isArray(tree)) return []; // 如果不是一个数组,则返回 for (let i = 0; i < tree.length; i++) { const node = tree[i]; result.push(node.id); // 存储当前节点的id if (Array.isArray(node.children)) { // 如果当前节点有子节点,则递归遍历子节点 getAllIds(node.children, result); } } return result; } 获取结果 console.log(getAllIds(datas, []), "getAllIds+++++++++"); 方法总结

这里的tree是树形数组,result是用来保存所有id的数组。

首先遍历当前层级的每个节点,将节点的id加入到result中。

如果节点还有子节点,就递归调用getAllIds函数获取子节点的id并将其合并到result数组中。

最后返回result数组。



【本文地址】


今日新闻


推荐新闻


CopyRight 2018-2019 办公设备维修网 版权所有 豫ICP备15022753号-3