如何使用JS从JSON树形结构按ID获取所有子孙节点生成指定格式数据
JS 实现指定ID后代节点ID收集功能
实现思路
- 采用广度优先遍历(BFS)遍历所有层级的后代节点,避免递归深度过深导致栈溢出问题
- 先定位目标根节点的基础属性,再逐层查询子节点ID存入结果数组
- 自动包含根节点自身ID,无后代时直接返回仅包含自身的children数组
完整实现代码
// 原始数据 const data = [{"id":63,"parent":59,"currency":1},{"id":64,"parent":59,"currency":1}, {"id":1,"parent":null,"currency":1},{"id":2,"parent":1,"currency":4}, {"id":4,"parent":3,"currency":4},{"id":3,"parent":2,"currency":2}, {"id":5,"parent":1,"currency":5},{"id":6,"parent":1,"currency":6}, {"id":7,"parent":3,"currency":2},{"id":8,"parent":1,"currency":1}, {"id":57,"parent":56,"currency":1},{"id":58,"parent":1,"currency":1}, {"id":59,"parent":1,"currency":1},{"id":30,"parent":1,"currency":1}, {"id":31,"parent":1,"currency":1},{"id":32,"parent":1,"currency":1}, {"id":33,"parent":1,"currency":1},{"id":34,"parent":1,"currency":1}, {"id":35,"parent":1,"currency":1},{"id":36,"parent":1,"currency":18}, {"id":37,"parent":1,"currency":1},{"id":39,"parent":1,"currency":1}, {"id":41,"parent":6,"currency":6},{"id":42,"parent":1,"currency":1}, {"id":43,"parent":42,"currency":1},{"id":48,"parent":47,"currency":2}, {"id":47,"parent":37,"currency":2},{"id":49,"parent":48,"currency":2}, {"id":52,"parent":1,"currency":16},{"id":9,"parent":1,"currency":9}, {"id":54,"parent":1,"currency":4},{"id":55,"parent":1,"currency":1}, {"id":56,"parent":1,"currency":1},{"id":19,"parent":1,"currency":12}, {"id":21,"parent":1,"currency":1},{"id":12,"parent":1,"currency":1}, {"id":13,"parent":1,"currency":1},{"id":15,"parent":1,"currency":1}, {"id":16,"parent":1,"currency":1},{"id":10,"parent":1,"currency":8}, {"id":11,"parent":1,"currency":4},{"id":66,"parent":1,"currency":1}, {"id":69,"parent":68,"currency":1},{"id":65,"parent":1,"currency":1}, {"id":68,"parent":1,"currency":1},{"id":70,"parent":1,"currency":11}]; /** * 根据输入ID获取所有后代节点ID并返回指定格式结果 * @param {number} targetId 要查询的目标ID * @param {Array} data 原始数据集 * @returns {Array} 符合要求的结果数组 */ function getNodeWithChildren(targetId, data) { // 查找目标根节点 const rootNode = data.find(item => item.id === targetId); if (!rootNode) return []; // 初始化children数组,先加入自身ID const childrenIds = [targetId]; // BFS队列初始化 const queue = [targetId]; while (queue.length > 0) { const currentId = queue.shift(); // 查找当前ID的所有直接子节点 const childNodes = data.filter(item => item.parent === currentId); childNodes.forEach(node => { childrenIds.push(node.id); queue.push(node.id); }); } // 组装结果 return [{ id: rootNode.id, currency: rootNode.currency, children: childrenIds }]; }
使用示例
// 测试ID=59 console.log(getNodeWithChildren(59, data)); // 输出:[{"id":59,"currency":1,"children":[59,63,64]}] // 测试ID=1 console.log(getNodeWithChildren(1, data)); // 输出的children数组将包含ID=1以及其所有后代节点ID
内容的提问来源于stack exchange,提问作者Raghul Ramkish
相关产品推荐
相关产品推荐

