简体   繁体   English

使用传播运算符将对象推入数组吗?

[英]Push an object into the array using spread operator?

I have an array of object like this, 我有一个这样的对象数组,

let array1 = [{id:1,name:'One'}]

whenever i do api call, the array of objects getting updated like this 每当我进行api调用时,对象数组都会像这样更新

let array2 = [{id:1,name:'One'}, {id:2, name:'Two'}]

for third time, it will be like this, 第三次,会是这样,

let array3 = [{id:1,name:'One'}, {id:2, name:'Two'}, {id:3, name: 'Three'}]

Now am trying to add key value pair for every object inside the array as 现在我试图为数组中的每个对象添加键值对,如下所示:

obj = {
    key: 'value'
}
[...array1, obj]

am getting an output like [{id:1,name:'One'},{key: 'value'}] 正在获得类似[{id:1,name:'One'},{key: 'value'}]

but the expected output is [{id:1,name:'One',key: 'value'}] that object should be pushed into an array after every api call 但预期的输出为[{id:1,name:'One',key: 'value'}]该对象应在每次api调用后被推入数组

If you want to add a key value pair to every object within the array, you need to map over the array apart from using spread syntax 如果要将键值对添加到数组中的每个对象,则除了使用扩展语法外,还需要映射到数组

 let array1 = [{id:1,name:'One'}] const obj = { key: 'value' } array1 = array1.map(val => ({...val, ...obj})) console.log(array1); 

If you want all the array items to be merged with the object, you can try with Array.prototype.map() and Object.assign() like the following way: 如果希望所有数组项都与对象合并,则可以尝试使用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); 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM