假设我有一个数组:
var myArr = [
{a: {'one': 1} },
{b: {'two': 2} },
{a: {'three': 3} },
{c: {'four': 4} },
{d: {'five': 5} }
];
我想创建一个这样的对象:
let myObj = {};
myObj = {
a: {
'one': 1,
'three': 3
},
b: {'two': 2},
c: {'four': 4},
d: {'five': 5}
}
该属性'a'
将被覆盖。如何防止这种情况发生?
我面临的问题是如果我执行以下操作:
myArr.forEach((x) => {
myObj[Object.keys(x)[0]] = x[Object.keys(x)];
});
我得到结果:
{
"a": {"three": 3},
"b": {"two": 2},
"c": {"four": 4},
"d": {"five": 5}
}
您可以reduce
像这样使用:
var myArr = [ {a: {'one': 1} }, {b: {'two': 2} }, {a: {'three': 3} }, {c: {'four': 4} }, {d: {'five': 5} } ];
var myObj = myArr.reduce(function(obj, o) { // for each object o in the array myArr
var key = Object.keys(o)[0]; // get the key of the object o ('a', 'b', ...)
var subKey = Object.keys(o[key])[0]; // get the key of the object inside o ('one', 'two', ...)
if(!obj[key]) { // if there is no object for the key 'key' in the result object
obj[key] = {}; // then add one
}
obj[key][subKey] = o[key][subKey]; // then add an entry for the 'subKey' to the object under the key 'key' (with the value taken from o)
return obj;
}, {});
console.log(myObj);
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句