2

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

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'}]

but the expected output is [{id:1,name:'One',key: 'value'}] that object should be pushed into an array after every api call

John_ny
  • 767
  • 12
  • 33
  • 1
    Why do you think this is possible with the [spread](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Spread_syntax) [syntax](https://stackoverflow.com/questions/44934828/is-foo-an-operator-or-syntax)? – Andreas Aug 21 '19 at 05:21

2 Answers2

3

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);
Shubham Khatri
  • 270,417
  • 55
  • 406
  • 400
2

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:

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);
Mamun
  • 66,969
  • 9
  • 47
  • 59