Home>

Write a recursive function that creates an array newArr consisting of the age (age) of the users specified in arr.

let arr= {
    "ivanov": {
        age: 25,
        parent: {
            "ivanov-a": {
                age: 45
            },
            "ivanov-b": {
                age: 43,
                parent: {
                    "sergeev-a": {
                        age: 88,
                        parent: {
                            "lionenko": {}
                        }
                    },
                }
            }
        }
    },
    "kostenko": {
        age: 56,
        parent: {
            "ignatenko": {
            },
            "sniezko": {
                age: 45
            }
        }
    }
}
let newArr= [];

It turns out to display only two keys. Through for in it is impossible to reach the nested age.

function recursion (obj) {
    if (Object.keys (obj.age)) {
        newArr.push (obj.age);
    }
}
for (let key in arr) {
     recursion (arr [key]);
}
document.querySelector ('. out'). innerHTML= newArr;

Where in your example is recursion then?

nazarpunk2021-10-13 12:31:51

if (Object.keys (obj.age)) -you have a number in obj.age, it makes no sense to call Object.keys () for it, this static method must accept an object as an argument.

vsemozhebuty2021-10-13 12:36:17