Find highest ID in deeply nested array of objects
This code recursively checks through a deeply nested array of objects to extract the highest value of the id property. It doesn't work.
by kokkieh
JavaScript
const data = {
id: 1,
name: "John",
parent_id: null,
children: [{
id: 2,
name: "Tess",
parent_id: 1,
children: []
},
{
id: 3,
name: "Tom",
parent_id: 1,
children: [{
id: 4,
name: "Harry",
parent_id: 3,
children: [{
id: 7,
name: "Thabo",
parent_id: 4,
children: []
}]
},
{
id: 5,
name: "Mary",
parent_id: 3,
children: []
},
{
id: 6,
name: "Madge",
parent_id: 3,
children: []
}
]
}
]
}
let newUserID = 0;
const newID = ( root, idKey ) => {
if ( root.id > idKey ) {
console.log( "idKey going in = " + idKey );
idKey = root.id;
console.log( "root = " + root.id + " new idKey = " + idKey );
}
root.children.forEach( ( obj ) => {
newID( obj, idKey );
});
console.log( "idkey returned = " + idKey );
return idKey;
}
newUserID = newID( data, newUserID );
console.log( newUserID );