简体   繁体   English

如何将元素添加到数组中的 object

[英]how to add element to an object within an array

I am making a http request and getting back 2 sets of data.我正在发出 http 请求并取回 2 组数据。 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.我假设下面两个 arrays 具有相同的长度,并使用元素索引进行合并。

 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;)如果您需要更多详细信息,请询问;)

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

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