简体   繁体   中英

How to know at what level a child is in deeply nested object?

I have recursive function which prints every child in a deeply nested object.

 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: [] } ] } ] } function printTree(t) { if (t.children.length === 0) { return } t.children.forEach((child,index) => { console.log(child.name); printTree(child); }) } printTree(tree);
output : dashrath, sitesh, yadnesh, machindra, tanishka, amol, amit

and I want something like this 1st gen dashrath, 2nd gen sitesh, 3rd gen yadnesh, 1st gen machindra, 2nd gen tejas, 3rd gen tanishka, 2nd gen amol, 3rd gen amit

You could have the printTree function accept a depth parameter and increment it appropriately with each recursive call, something like this:

function printTree(t, depth = 0) {
    if (t.children.length === 0) {
        return
    }
    t.children.forEach((child,index) => {
        // you'd need to do some extra formatting here if you
        // want ordinals like "1st", "2nd", etc.
        console.log(`gen ${depth + 1}: ${child.name}`);                
        printTree(child, depth + 1);
    })
}
printTree(tree);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM