You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何遍历含children的JavaScript对象数组并输出所有ID?

遍历树形结构所有节点ID的解决方案

你的代码仅遍历了根数组的第一层节点,没有处理嵌套的children子节点。要获取所有层级的ID,需要遍历整个树形结构,以下是两种可行的实现方式:

方法一:递归遍历

递归是处理树形结构最直观的方式,通过函数自身调用处理子节点:

const root = [
    { id: "3", children: [] },
    { id: "8", children: [{ id: "476", children: [] }] }
];

const getAllIds = (nodes) => {
    const ids = [];
    
    const processNode = (node) => {
        // 收集当前节点ID
        ids.push(node.id);
        // 递归处理子节点(如果存在)
        if (node.children?.length) {
            node.children.forEach(processNode);
        }
    };

    // 处理传入的数组或单个节点
    Array.isArray(nodes) ? nodes.forEach(processNode) : processNode(nodes);
    
    return ids;
};

const idx = getAllIds(root);
console.log(idx); // 输出: ["3", "8", "476"]

方法二:迭代遍历(栈实现)

如果树形结构层级极深,递归可能导致栈溢出,此时可以用栈模拟递归过程,更稳定:

const root = [
    { id: "3", children: [] },
    { id: "8", children: [{ id: "476", children: [] }] }
];

const getAllIds = (nodes) => {
    const ids = [];
    const stack = [...nodes]; // 初始化栈,放入所有根节点

    while (stack.length > 0) {
        const node = stack.pop(); // 取出栈顶节点
        ids.push(node.id);
        
        // 将子节点倒序推入栈,保证遍历顺序和递归一致(不需要顺序可省略reverse)
        if (node.children?.length) {
            stack.push(...[...node.children].reverse());
        }
    }

    return ids;
};

const idx = getAllIds(root);
console.log(idx); // 输出: ["3", "8", "476"]

内容的提问来源于stack exchange,提问作者khalid seleem

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.18 20:00:37