json 如何在同一个数组中添加两个数组对象?

dvtswwa3  于 2023-02-06  发布在  其他
关注(0)|答案(3)|浏览(162)

例如,我有两个具有不同列名和值的数组对象,我希望它们位于相同的索引中

let a = [{name: 'asha', age:20, mother: "sushi", father: "Nick"}]
let b = [{class: "10th", Sub: "science", Marks: 30}]

我想把它们合并成一个数组,就像这样

[{name: 'asha', age:20, mother: "sushi", father: "Nick", class: "10th", Sub: "science"}]
hs1ihplo

hs1ihplo1#

您可以使用Array#map以扩展语法合并相同索引处的元素。

let a = [{name: 'asha', age:20, mother: "sushi", father: "Nick"}], b = [{class: "10th", Sub: "science", Marks: 30, }]
let res = a.map((x, i) => ({...x, ...b[i]}));
console.log(res);
inb24sb2

inb24sb22#

假设两个数组具有相同的长度,则可以对相应的元素使用带有spread运算符的for循环

const combined = [];
for(let i...) {
  combined.push({ ...arr1[i], arr2[i]});
}
pvabu6sv

pvabu6sv3#

可以按如下方式使用Array#forEach

const
     a = [{name: 'asha', age:20, mother: "sushi", father: "Nick"}],
     b = [{class: "10th", Sub: "science", Marks: 30}],
     c = [];
     
a.forEach((val, i) => c.push({...val,...b[i]}));

console.log( c );

相关问题