转化嵌套对象数组 [英] Transforming nested objects to an array
本文介绍了转化嵌套对象数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个包含其它的目的,如一个对象
I have an object that contains other objects, such as:
let foo = {
a: {
b: {},
c: {}
},
d: {
e: {}
}
};
现在我想转换成对象,其中前两个层次的按键形成一个键/值对,如数组这样的:
Now I want to transform this into an array of objects, where the keys of the first two levels form a key / value pair, such as:
let transformedFoo = [
{ outer: 'a', inner: 'b' },
{ outer: 'a', inner: 'c' },
{ outer: 'd', inner: 'e' }
];
我目前的做法是这样的:
My current approach looks like this:
let fooTransformed = [];
Object.keys(foo).forEach(function (outerKey) {
Object.keys(foo[outerKey]).forEach(function (innerKey) {
fooTransformed.push({
outer: outerKey,
inner: innerKey
});
});
});
它的工作原理,但我认为这不是好(即,它不是最好有两个嵌套循环)。是否有关于如何实现这更好的方式(我可以想像,有一个相当考究单纯的功能性解决方案,但我想不出任何)?
It works, but I think it's not "nice" (i.e., it's not nice to have two nested loops). Is there a better way on how to achieve this (I could imagine that there is a quite elegant purely functional solution, but I can't think of any)?
推荐答案
使用地图和减少:
> Object.keys(foo).map(function(key) {
return Object.keys(foo[key]).map(function(val) {
return {outer: key, inner: val} } )
}).reduce(function(a,b) { return a.concat(b) })
[ { outer: 'a', inner: 'b' },
{ outer: 'a', inner: 'c' },
{ outer: 'd', inner: 'e' } ]
这篇关于转化嵌套对象数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文