1

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 :)

5
  • 5
    what, if you have more than one with the same length? please add your try. Commented Mar 27, 2019 at 13:17
  • why would you want that? And how are you going to test for it? Meaning are you going to pass the actual (last) object and try to get the path to it, or some other way? Commented Mar 27, 2019 at 13:19
  • Is the content of mango ({}) acceptable instead of the path to it? Commented Mar 27, 2019 at 13:26
  • @NinaScholz ideally, i would need all possibilities of max length. i'm trying with a recursive function, but couldn't figure out how to keep track of nested keys. Commented Mar 27, 2019 at 13:28
  • @Kognise no. its the keys that are important. Commented Mar 27, 2019 at 13:29

2 Answers 2

3

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.

Sign up to request clarification or add additional context in comments.

3 Comments

If there are multiple path in deepest level, it will chose the first one. right?
This works. the only issue with this is not returning multiple paths in case of same length.
I edited my code so that it can return multiple paths in case of same depth. Please take a look.
0

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('.')));

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.