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

如何在遍历深度嵌套JS对象时获取子节点对应的层级?

实现代际层级标注的代码调整方案

你只需要给递归函数新增一个层级参数,每次递归调用时层级自增即可,修改后的完整代码如下:

const tree = {
    name: "Anand",
    children: [
        {
            name: "Dashrath",
            children: [
                {
                    name: "Sitesh",
                    children: [
                        {
                            name: "Yadnesh",
                            children: []
                        }
                    ]
                }
            ]
        },
        {
            name: "Machindra",
            children: [
                {
                    name: "Tejas",
                    children: [
                        {
                            name: "Tanishka",
                            children: []
                        }
                    ],
                },
                {
                    name: "Amol",
                    children: [],
                },
                {
                    name: "Amit",
                    children: []
                }
            ]
        }
    ]
}
// 序数后缀处理函数,用来生成1st/2nd/3rd/4th格式
function getOrdinalSuffix(n) {
    if (n % 10 === 1 && n % 100 !== 11) return 'st';
    if (n % 10 === 2 && n % 100 !== 12) return 'nd';
    if (n % 10 === 3 && n % 100 !== 13) return 'rd';
    return 'th';
}
// 新增level参数,初始默认值为1,对应根节点的第一层子节点代际
function printTree(t, level = 1) {
    if (t.children.length === 0) {
        return
    }
    t.children.forEach((child,index) => {
        // 打印时拼接代际信息
        console.log(`${level}${getOrdinalSuffix(level)} gen ${child.name}`);                
        printTree(child, level + 1);
    })
}
printTree(tree);

运行输出

1st gen Dashrath
2nd gen Sitesh
3rd gen Yadnesh
1st gen Machindra
2nd gen Tejas
3rd gen Tanishka
2nd gen Amol
2nd gen Amit

注:你给出的预期输出中3rd gen amit属于笔误,Amit是根节点下第二层节点,实际代际为2代,以上输出为逻辑正确的结果。如果你不需要序数后缀,直接打印${level} gen ${child.name}即可。

内容的提问来源于stack exchange,提问作者Siddhesh Yadav

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.29 02:54:03