简体   繁体   中英

how to add element to an object within an array

I am making a http request and getting back 2 sets of data. They are both an array of objects. I want to add the one element from the one array to the other. So, the one array looks like this for example:

[
 { name: 'Bob', age: '21'}
 { name: 'Sue', age: '34'}
]

Then the other one looks like this:

[
 { gender: 'male'}
 { gender: 'female'}
]

I tried joining them like this:

const arr = [...arr1, ...arr2];

But that gave me:

[
 { gender: 'male' }
 { gender: 'female' }
 { name: 'Bob', age: '21'}
 { name: 'Sue', age: '34'}
]

It should look like:

[
 { name: 'Bob', age: '21', gender: 'male' }
 { name: 'Sue', age: '34', gender: 'female'}
]

How can I achieve this?

I assume below two arrays have same length, and use element index for merging.

 let data1 = [ { name: 'Bob', age: '21'}, { name: 'Sue', age: '34'} ]; let data2=[ { gender: 'male'}, { gender: 'female'} ]; // basically merge objects with same index from both arrays, using object spread operator let result = data1.map((x,i)=>({...x, ...data2[i] })); console.log(result)

you should use it this way

const arr1 = [{name:'BOB', age:'24'},{name:"jennyfer", age:'27'}]
const arr2= [{gender:'male'},{gender:'female'}]

const newArray = [{...arr1[0],gender:arr2[0].gender}, {...arr1[1],...arr2[1]}]


console.log(newArray)

if you need more details ask;)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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