【发布时间】:2019-07-03 18:16:40
【问题描述】:
我的问题与Add key value pair to all objects in array有关
但是,当我尝试分配对象而不是字符串、int 等时,解决方案不起作用。
我尝试在 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; }
【问题讨论】:
-
什么是
arrObjects?你能把剩下的代码贴出来吗? -
另外,你可能会澄清你的意思是什么不起作用。你在期待什么?发生了什么?
-
在使用
map时不应该改变原始数组。改用:arrObjects.map(item => ({...item, newKey: {...obj}}));
标签: javascript arrays function object ecmascript-6