-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

0

2 Answers 2

1

You can do use map and the spread operator

arr1.map((x, i) => ({...x, ...arr2[i]}));
Sign up to request clarification or add additional context in comments.

Comments

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)

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.