skip to Main Content

I would like to know how to merge two array of objects into single array using javascript

var arr1 = [
  {id:1, name: "xxx"}
]

var arr2 =[
 {details:"finance", cost:"100"}
]

Tried.
var result1 = [...arr1, ...arr2];
var result=Object.assign({}, ...result1)



Expected Output
[
{
id:1,
name: "xxx",
details:"finance",
cost:"100"
}
]

3

Answers


  1. var arr1 = [
      {id:1, name: "xxx"}
    ]
    
    var arr2 =[
     {details:"finance", cost:"100"}
    ]
    
    const result = arr1.map((item, index) => ({ ...item, ...arr2[index] }))
    
    console.log(result)
    Login or Signup to reply.
  2. Just inner-wrap you [...arr1, ...arr2] in curly braces and access via array index: [{...arr1[0], ...arr2[0]}]

    var arr1 = [
      {id:1, name: "xxx"}
    ]
    
    var arr2 =[
     {details:"finance", cost:"100"}
    ]
    
    var result1 = [{...arr1[0], ...arr2[0]}];
    
    console.log(result1)
    Login or Signup to reply.
  3. You can also concat both arrays and then reduce the whole array to assign to a new object:

    var arr1 = [
      {id:1, name: "xxx"}
    ]
    
    var arr2 =[
     {details:"finance", cost:"100"}
    ]
    
    const result = arr1.concat(arr2).reduce(((r, c) => Object.assign(r, c)), {});
    console.log(result)

    I prefer this because you can add as many arrays as you want to the concat function.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search