I keep running into trouble when working with ObjectIds and lodash. Say I have two arrays of objects I want to use lodash _.unionBy()
with:
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');
Result
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',
},
]
*/
Desired result
[
{
_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',
},
]
Since ObjectIds are objects and they are not pointing to the same reference in many cases (e.g. when fetching documents from MongoDB and comparing with local seed for testing), I cannot use '_id' as iteratee.
How do I use lodash with ObjectIDs to achieve desired results?