我的问题与 Add key value pair to all objects in array 有关
但是,当我尝试分配对象而不是字符串、整数等时,解决方案不起作用。
我尝试在 map 函数中创建新键,但它只适用于非对象变量。
这行得通
arrObjects.map(item => item.newKey = 'xxx')
这不是
var obj = { a: 'a', b: 'b', c: 'c' }
arrObjects.map(item => item.newKey = obj)
输出:
var arrOfObj = [{
name: 'eve'
}, {
name: 'john'
}, {
name: 'jane'
}];
var obj = {
a: 'a',
b: 'b',
c: 'c'
}
arrOfObj.map(item => item.newKey = obj);
console.log(arrOfObj);
.as-console-wrapper { max-height: 100% !important; top: 0; }
最佳答案
您需要创建对象的副本。默认情况下,对象被指定为引用。
这里...
用于创建浅拷贝
var arrOfObj = [{name: 'eve'}, {name: 'john'}, { name: 'jane'}];
var obj = { a: 'a', b: 'b', c: 'c'}
arrOfObj.forEach(item => (item.newKey = {...obj}));
console.log(arrOfObj);
.as-console-wrapper { max-height: 100% !important; top: 0; }
您可以看到一些用例 here
关于javascript - 将键值(对象)对添加到数组中的所有对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54610469/