假设我有一个数组:
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}
}
最佳答案
为此,您可以在循环中使用 Object.assign
,请参阅评论:
var myArr = [
{a : {'one':1}},
{b: {'two':2}},
{a : {'three':3}},
{c : {'four':4}},
{d:{'five':5}}
];
let myObj = {};
myArr.forEach(entry => {
// Get the first key in the object
const key = Object.keys(entry)[0];
// Merge the object in `myObj[key]` with the one in `entry[key]`; it's okay
// if there's no `myObj[key]`, `Object.assign` will skip over `undefined`
myObj[key] = Object.assign({}, myObj[key], entry[key]);
});
console.log(myObj);
.as-console-wrapper {
max-height: 100% !important;
}
这不是非常高效,它会不必要地重新创建对象,但除非您在成千上万个对象的紧密循环中执行此操作,否则这无关紧要。如果你是,我们只是在迭代器回调中分支:
var myArr = [
{a : {'one':1}},
{b: {'two':2}},
{a : {'three':3}},
{c : {'four':4}},
{d:{'five':5}}
];
let myObj = {};
myArr.forEach(entry => {
// Get the first key in the object
const key = Object.keys(entry)[0];
const src = entry[key];
const dest = myObj[key];
if (!dest) {
// Create a copy of the object and remember it
myObj[key] = Object.assign({}, src);
} else {
// Copy properties from the source to the existing target
Object.keys(src).forEach(k => {
dest[k] = src[k];
});
}
});
console.log(myObj);
.as-console-wrapper {
max-height: 100% !important;
}
关于javascript - 如何动态地为对象的相同属性赋值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47620082/