0

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

1 Answer 1

1

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;}

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.