bzlight
bzlight

Reputation: 1160

Merge two arrays of Objects by value returned from MongoDB

Problem

I need to merge two arrays that are returned from MongoDB by value, however all of the methods I've tried that work with regular javascript arrays aren't working properly. Your help would be greatly appreciated

Arrays

array1 = [ { _id: 5c6c7132f9bf4bdab9c906ff,
    user: 5c65d9438e4a834c8e85dd7d },
  { _id: 5c6ccd6d3a0dc4e4951c2bee,
    user: 5c65d9438e4a834c8e85dd7e } ]

array2 = users [ { _id: 5c65d9438e4a834c8e85dd7d,
    info: { name: 'John', city: 'New York' } },
  { _id: 5c65d9438e4a834c8e85dd7e,
    info: { name: 'Paneer', city: 'San Fran' } } ]

Desired Result

mergedArray = [ { _id: 5c6c7132f9bf4bdab9c906ff,
    user: 5c65d9438e4a834c8e85dd7d,
    info: { name: 'John', city: 'New York' } } ,
  { _id: 5c6ccd6d3a0dc4e4951c2bee,
    user: 5c65d9438e4a834c8e85dd7e, 
    info: { name: 'Paneer', city: 'San Fran' } } ]

What I've tried

  1. _.merge from lodash
  2. _.map & _.extend from lodash
  3. A variety of vanilla javascript .map functions that

Upvotes: 0

Views: 32

Answers (1)

Shidersz
Shidersz

Reputation: 17190

One possible solution is to use Array.map() over array1 and get the related info data from the array2 with Array.find():

const array1 = [
  {_id: '5c6c7132f9bf4bdab9c906ff', user: '5c65d9438e4a834c8e85dd7d'},
  {_id: '5c6ccd6d3a0dc4e4951c2bee', user: '5c65d9438e4a834c8e85dd7e'}
];

const array2 = [
  {
    _id: '5c65d9438e4a834c8e85dd7d',
    info: { name: 'John', city: 'New York' }
  },
  {
    _id: '5c65d9438e4a834c8e85dd7e',
    info: { name: 'Paneer', city: 'San Fran' }
  }
];

let merged = array1.map(
    o => ({...o, info: array2.find(({_id}) => _id === o.user).info})
);

console.log(merged);
.as-console {background-color:black !important; color:lime;}
.as-console-wrapper {max-height:100% !important; top:0;}

Upvotes: 1

Related Questions