问题
我需要按值合并从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' } } ]
我尝试过的
答案 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;}