Home > OS >  How to add two array object in same array?
How to add two array object in same array?

Time:02-03

For example, I have two array object with different column names and values and I want them to be at same index

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

and c should be

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

CodePudding user response:

You can use Array#map to combine elements at the same index with spread syntax.

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);

CodePudding user response:

Assuming both arrays have the same length, you can use a for loop with the spread operator on corresponding elements

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