如何获取javascript嵌套对象中最深层嵌套对象的键(路径)

时间:2019-03-27 13:15:31

标签: javascript javascript-objects

我有一个这样的嵌套javascript对象:

{
    "apple": {
        "orange": {
            "chilli": {},
            "pineapple": {
                "mango": {}
            }
        },
        "carrot": {
            "cabbage": {},
            "onion": {}
        }
    }
}

我想获取最深的嵌套对象的路径(键)。像apple.orange.pineapple.mango

需要任何帮助:)

2 个答案:

答案 0 :(得分: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)

上述函数递归地遍历整个对象,并根据深度进行比较。如果depth大于之前遇到的任何键(我使用全局变量进行了检查,这不是一个好习惯),它将更新深度和路径。如果存在另一个具有相同maxDepth的键,则它也将添加到maxPaths列表中。递归完成后,您的maxLevelmaxPaths变量会为您提供最深的键及其路径和级别。

答案 1 :(得分:1)

您可以返回路径最长的数组数组。

这适用于多个具有相同长度的路径。

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