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 :)
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, yourmaxLevel
andmaxPaths
variables gives you the deepest key with its path and level.You could return an array of arrays with the longest pathes.
This works for more than one path with the same length.