skip to Main Content

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 I want to merge these into a single array like this:

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

3

Answers


  1. 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);
    Login or Signup to reply.
  2. 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]});
    }
    
    Login or Signup to reply.
  3. You can use Array#forEach as follows:

    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 );
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search