If I have an object with multiple child properties:
let obj = { a: "a", b: { c: "c", d: { e: "e" } } }
how can I get an object property's depth:
eg. "e" property depth is 4 (or 3) obj.b.d.e
CodePudding user response:
A recursive method initialising depth
as 1
, using a separate function to check whether something is an actual object (given that almost everything in JS is of type "object").
const obj = { a: "a", b: { c: "c", d: { e: "e" } } }
function isObject(obj) {
return Object.prototype.toString.call(obj) === '[object Object]';
}
function getDepth(obj, query, depth = 1) {
if (!isObject(obj)) return 'Not an object';
for (const [key, value] of Object.entries(obj)) {
if (key === query) return `Found ${query} at depth ${depth}`;
if (isObject(value)) return getDepth(value, query, depth);
}
return 'No property matching query';
}
console.log(getDepth(obj, 'b'));
console.log(getDepth(obj, 'c'));
console.log(getDepth(obj, 'e'));