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

1
  • 1
    Why do you think this is possible with the spread syntax? Commented Aug 21, 2019 at 5:21

2 Answers 2

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);

Sign up to request clarification or add additional context in comments.

Comments

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);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.