如何获取javascript嵌套对象中最深层嵌套对象的键(路径) [英] How to get keys (path to) the deepest nested object in a javascript nested object
本文介绍了如何获取javascript嵌套对象中最深层嵌套对象的键(路径)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个嵌套的javascript对象,如下所示:
I have a nested javascript object like this:
{
"apple": {
"orange": {
"chilli": {},
"pineapple": {
"mango": {}
}
},
"carrot": {
"cabbage": {},
"onion": {}
}
}
}
我想获取最深的嵌套对象的路径(键).类似于apple.orange.pineapple.mango
i want to get the path (keys) of the deepest nested object. something like apple.orange.pineapple.mango
需要任何帮助:)
推荐答案
您可以返回路径最长的数组数组.
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('.')));
这篇关于如何获取javascript嵌套对象中最深层嵌套对象的键(路径)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文