I have a nested javascript object like this:
{
"apple": {
"orange": {
"chilli": {},
"pineapple": {
"mango": {}
}
},
"carrot": {
"cabbage": {},
"onion": {}
}
}
}
i want to get the path (keys) of the deepest nested object. something like apple.orange.pineapple.mango
any help is appriciated :)
You could return an array of arrays with the longest pathes.
This works for more than one path with the same length.
function getDeepest(object) {
return object && typeof object === 'object'
? Object.entries(object).reduce((r, [k, o]) => {
var temp = getDeepest(o).reduce((r, a, i) => {
if (!i || r[0].length < a.length) return [a];
if (r[0].length === a.length) r.push(a);
return r;
}, []);
return temp.length
? [...r, ...temp.map(t => [k].concat(t))]
: [...r, [k]];
}, [])
: [];
}
var object = { apple: { orange: { chilli: {}, pineapple: { mango: {} } }, carrot: { cabbage: {}, onion: {} } } };
console.log(getDeepest(object).map(a => a.join('.')));
var object = {
"apple": {
"orange": {
"chilli": {},
"pineapple": {
"mango": {}
}
},
"carrot": {
"cabbage": {
"cherries":{}
},
"onion": {}
}
}
}
var maxLevel = 0;
var maxPaths = [];
function findDeepest(obj, level, path) {
var keys = Object.keys(obj) // get keys
for(var i=0; i< keys.length; i++) {
var newPath = level !== 0 ? path + "." + keys[i] : keys[i] // construct path string
// Recursively call
findDeepest(obj[keys[i]], level + 1, newPath )
}
if (level > maxLevel) { // There is a deeper key
maxLevel = level
maxPaths = [path] // create a fresh list
} else if (level === maxLevel) {
maxPaths.push(path) // add key to the list, as it has the same depth
}
}
findDeepest(object, 0, "")
console.log(maxLevel)
console.log(maxPaths)
The above function recursively traverses whole object, and makes comparison based on depth. If depth is greater than any key encountered before (I checked this with global variables which is not a good practice), it updates the depth and path. If there is another key with same maxDepth, then it is added to maxPaths
list as well. After the recursion finishes, your maxLevel
and maxPaths
variables gives you the deepest key with its path and level.