简体   繁体   中英

How to add an property to an existing object inside an array

For example this is the original array

[
 {name:xyz,id:123 },
 {name:abc,id:232},
] 

Now here is an another array

[
 {value:'anything'},
 {value:'anything12312'}
]

Now in new array or original array the output should be this

[
 {value:'anything',name:xyz,id:123},
 {value:'anything12312', name:abc,id:232}}
]

How can I achieve this

you mean like this??

Use map ,index and spread as:

 let a = [ {name:"xyz",id:123 }, {name:"abc",id:232}, ] let b = [ {value:'anyrhing'}, {value:'anything12312'} ] let res = a.map((el,idx)=> ({...el,...b[idx]})); console.log(res)

Use object destructuring.


const arr1 = [
 {name:'xyz',id:123 },
 {name:'abc',id:232},
] 

const arr2 = [
 {value:'anyrhing'},
 {value:'anything12312'}
]

const arr3 = [];
for(let i=0;i<arr1.length;i++)
  arr3.push({...arr2[i],...arr1[i]});
A1=[
    {name:"xyz",id:123 },
    {name:"abc",id:232},
   ];
A2=[
    {value:'anyrhing'},
    {value:'anything12312'}
   ];

obj1={
    ...A2[0],
    ...A1[0]}

//another method to merge objects

obj2=Object.assign(A2[1],A1[1]);

//The result you needed

A3=[obj1,obj2];

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