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

时光毁灭记忆、已成空白 提交于 2019-12-06 13:40:56

问题


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


回答1:


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



回答2:


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.



来源:https://stackoverflow.com/questions/55378137/how-to-get-keys-path-to-the-deepest-nested-object-in-a-javascript-nested-objec

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!