Search code examples
javascriptjavascript-objects

How to get keys (path to) the deepest nested object in a javascript nested object


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


Solution

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