I have two arrays of objects.
arr1 = [
{
myName: 'Adam',
mySkill: 'CSS',
},
{
myName: 'Mutalib',
mySkill: 'JavaScript',
},
];
arr2 = [
{
myName: 'Adam',
myWeight: '112',
},
{
myName: 'Habib',
myWeight: '221',
},
];
The result I want is an array that contains objects of first array that have a matching property "myName" in second array, with the additional properties of the corresponding second array object.
result = [
{
myName = 'Adam'
mySkill = 'CSS'
myWeight = '112'
}
];
The solution below groups the concatenated array (arr1
and arr2
) by myName
, removes all groups that only contains one item using reject, and lastly use map to merge the resulting array.
var result = _(arr1)
.concat(arr2)
.groupBy('myName')
.reject({ length: 1 })
.map(_.spread(_.merge))
.value();
var arr1 = [
{
myName: 'Adam',
mySkill: 'CSS',
},
{
myName: 'Mutalib',
mySkill: 'JavaScript',
}
];
var arr2 = [
{
myName: 'Adam',
myWeight: '112',
},
{
myName: 'Habib',
myWeight: '221',
}
];
var result = _(arr1)
.concat(arr2)
.groupBy('myName')
.reject({ length: 1 })
.map(_.spread(_.merge))
.value();
console.log(result);
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.4/lodash.js"></script>
An alternative solution is to use intersectionWith to get the intersection between two arrays and assign the missing values at the same time. Note the use of cloneDeep to promote immutability.
var result = _.intersectionWith(_.cloneDeep(arr1), arr2, function(x, y) {
return x.myName === y.myName && _.assign(x, y);
});
var arr1 = [
{
myName: 'Adam',
mySkill: 'CSS',
},
{
myName: 'Mutalib',
mySkill: 'JavaScript',
}
];
var arr2 = [
{
myName: 'Adam',
myWeight: '112',
},
{
myName: 'Habib',
myWeight: '221',
}
];
var result = _.intersectionWith(_.cloneDeep(arr1), arr2, function(x, y) {
return x.myName === y.myName && _.assign(x, y);
});
console.log(result);
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.4/lodash.js"></script>
Alternative native JS solution using Array.prototype.forEach
and Object.assign
functions:
var arr1 = [
{ myName: 'Adam', mySkill: 'CSS'}, { myName: 'Mutalib', mySkill: 'JavaScript'},
],
arr2 = [
{ myName: 'Adam', myWeight: '112'}, { myName: 'Habib', myWeight: '221'}
],
result = [];
arr1.forEach(function (o) {
arr2.forEach(function (c) {
if (o.myName === c.myName) result.push(Object.assign({}, o, c));
})
});
console.log(result);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With