-2

I would like to merge two different array of objects to one, as follows:

Array 1:

[ { id: 1,
    fullName: '...',
    districtName: '...',
    cityName: '...',
    placeName: '...',
    geoLat: '...',
    geoLong: '...' },
{ id: 2,
    fullName: '...',
    districtName: '...',
    cityName: '...',
    placeName: '...',
    geoLat: '...',
    geoLong: '...' },
]

Array 2:

[ { a:'...',
    b:'...',
    c:'...',
  },
  { d:'...',
    e:'...',
    f:'...',
  }
]         

Array 1 and array 2 have same length. I would like to merge them correspondely, as follows:

[ { id: 1,
    fullName: '...',
    districtName: '...',
    cityName: '...',
    placeName: '...',
    geoLat: '...',
    geoLong: '...',
    a:'...',
    b: '...',
    c: '...' },
{ id: 2,
    fullName: '...',
    districtName: '...',
    cityName: '...',
    placeName: '...',
    geoLat: '...',
    geoLong: '...',
    d:'...',
    e: '...',
    f: '...' },
]

How would I do this? I've thought about using map, but that way I can only iterate through one array. I have to iterate both array and merge them.

Any suggestions are helpful. Thank you

Eric Ahn
  • 391
  • 2
  • 7
  • 18

2 Answers2

1

You can use nested forEach loops to assign values from second array to the first one.

var a = [{
    id: 1,
    fullName: '...',
    districtName: '...',
    cityName: '...',
    placeName: '...',
    geoLat: '...',
    geoLong: '...'
  },
  {
    id: 2,
    fullName: '...',
    districtName: '...',
    cityName: '...',
    placeName: '...',
    geoLat: '...',
    geoLong: '...'
  },
]

var b = [{
    a: '...',
    b: '...',
    c: '...',
  },
  {
    d: '...',
    e: '...',
    f: '...',
  }
]
a.forEach(function(e, j) {
  Object.keys(b[j]).forEach(function(x) {
    e[x] = b[j][x];
  })
})
console.log(a)
ellipsis
  • 12,049
  • 2
  • 17
  • 33
1

You can do use map and the spread operator

arr1.map((x, i) => ({...x, ...arr2[i]}));
Abito Prakash
  • 4,368
  • 2
  • 13
  • 26