如何向数组内的现有对象添加属性

例如这是原始数组


[

 {name:xyz,id:123 },

 {name:abc,id:232},

现在这是另一个数组


[

 {value:'anything'},

 {value:'anything12312'}

]

现在在新数组或原始数组中,输出应该是这样的


[

 {value:'anything',name:xyz,id:123},

 {value:'anything12312', name:abc,id:232}}

]

我怎样才能实现这个目标


RISEBY
浏览 115回答 3
3回答

缥缈止盈

你的意思是这样?使用地图、索引和传播作为: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)

大话西游666

使用对象解构。const arr1 = [&nbsp;{name:'xyz',id:123 },&nbsp;{name:'abc',id:232},]&nbsp;const arr2 = [&nbsp;{value:'anyrhing'},&nbsp;{value:'anything12312'}]const arr3 = [];for(let i=0;i<arr1.length;i++)&nbsp; arr3.push({...arr2[i],...arr1[i]});

慕田峪7331174

A1=[&nbsp; &nbsp; {name:"xyz",id:123 },&nbsp; &nbsp; {name:"abc",id:232},&nbsp; &nbsp;];A2=[&nbsp; &nbsp; {value:'anyrhing'},&nbsp; &nbsp; {value:'anything12312'}&nbsp; &nbsp;];obj1={&nbsp; &nbsp; ...A2[0],&nbsp; &nbsp; ...A1[0]}//another method to merge objectsobj2=Object.assign(A2[1],A1[1]);//The result you neededA3=[obj1,obj2];
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript