【发布时间】:2018-08-25 12:08:01
【问题描述】:
在使用 ObjectIds 和 lodash 时,我总是遇到麻烦。假设我有两个对象数组,我想将 lodash _.unionBy() 与:
var arr1 = [
{
_id: ObjectId('abc123'),
old: 'Some property from arr1',
},
{
_id: ObjectId('def456'),
old: 'Some property from arr1',
},
];
var arr 2 = [
{
_id: ObjectId('abc123'),
new: 'I want to merge this with object in arr1',
},
{
_id: ObjectId('def456'),
new: 'I want to merge this with object in arr1',
},
];
var res = _.unionBy(arr1, arr2, '_id');
结果
console.log(res);
/*
[
{
_id: ObjectId('abc123'),
old: 'Some property from arr1',
},
{
_id: ObjectId('def456'),
old: 'Some property from arr1',
},
{
_id: ObjectId('abc123'),
new: 'I want to merge this with object in arr1',
},
{
_id: ObjectId('def456'),
new: 'I want to merge this with object in arr1',
},
]
*/
想要的结果
[
{
_id: ObjectId('abc123'),
old: 'Some property from arr1',
new: 'I want to merge this with object in arr1',
},
{
_id: ObjectId('def456'),
old: 'Some property from arr1',
new: 'I want to merge this with object in arr1',
},
]
由于 ObjectId 是对象,并且在许多情况下(例如,从 MongoDB 获取文档并与本地种子进行比较以进行测试时),它们并不指向相同的引用,因此我不能使用 '_id' 作为迭代对象。
如何使用带有 ObjectID 的 lodash 来达到预期的效果?
【问题讨论】:
-
我猜你需要像
_.unionBy(... x => String(x._id))这样的东西
标签: javascript mongodb lodash