根据从MongoDB返回的值合并两个对象数组

时间:2019-04-17 21:30:00

标签: javascript arrays mongodb mongoose

问题

我需要按值合并从MongoDB返回的两个数组,但是我尝试使用常规javascript数组的所有方法均无法正常工作。

数组

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' } } ]

所需结果

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

我尝试过的

  1. _。来自lodash的合并
  2. _。map和_.extend from lodash
  3. 各种普通的javascript .map函数

1 个答案:

答案 0 :(得分:1)

一种可能的解决方案是在array1上使用Array.map()并通过Array.find()info获取相关的array2数据:

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