我有一个这样的对象数组,
let array1 = [{id:1,name:'One'}]
每当我进行api调用时,对象数组都会像这样更新
let array2 = [{id:1,name:'One'}, {id:2, name:'Two'}]
第三次,就像这样
let array3 = [{id:1,name:'One'}, {id:2, name:'Two'}, {id:3, name: 'Three'}]
现在我正尝试为数组中的每个对象添加键值对
obj = {
key: 'value'
}
[...array1, obj]
am得到类似[{id:1,name:'One'},{key: 'value'}]
但是预期的输出为[{id:1,name:'One',key: 'value'}]
,即在每次api调用之后都应将对象推入数组
答案 0 :(得分:3)
如果要将键值对添加到数组中的每个对象,则除了使用扩展语法之外,还需要映射到数组
let array1 = [{id:1,name:'One'}]
const obj = {
key: 'value'
}
array1 = array1.map(val => ({...val, ...obj}))
console.log(array1);
答案 1 :(得分:2)
如果您希望所有数组项都与对象合并,则可以使用Array.prototype.map()
和Object.assign()
进行尝试,如下所示:
let array3 = [{id:1,name:'One'}, {id:2, name:'Two'}, {id:3, name: 'Three'}];
let obj = {key: 'value'};
let res = array3.map(i => Object.assign(i, obj));
console.log(res);