I have a nested object like
{
name: "John",
parent:{
parent:{
parent:{
}
}
}
}
Now I want to get the level of the master parent object or basically how many times a parent object has been nested. In this case, I should be getting an output of 3.
You could also do it recursively like this:
const obj = {
name: "John",
parent:{
parent:{
parent:{
parent:{
parent:{
parent:{
}
}
}
}
}
}
}
function findk(o,k,l=0){
if (o[k]) l=findk(o[k],k,++l)
return l
}
console.log(findk(obj,"parent"))
You could taken a recursive and iterative approach by checkin the handed over value, if it is an array, then check for wanted key and iterate all values of the array or return zero.
const
getCount = (object, key) => object && typeof object === 'object'
? (key in object) + Object
.values(object)
.reduce((s, o) => s + getCount(o, key), 0)
: 0;
console.log(getCount({ name: "John", parent: { parent: { parent: {} } } }, 'parent'));
let obj = { // treat it like a tree
name: "John",
parent: {
parent: {
parent: {}
}
}
}
const findDepth = (root, key) => {
let depth = 0;
let loop = (obj) => {
if (obj && obj[key]) {
loop(obj[key]);
depth++;
}
}
loop(root);
return depth;
}
const result = findDepth(obj, 'parent')
console.log(result);