Last active
June 10, 2022 14:00
-
-
Save phunguyen19/8f047e9733f54ab7cc0b481b38fc8631 to your computer and use it in GitHub Desktop.
js lodash merge 2 arrays of object by key
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Source reference: https://stackoverflow.com/questions/38612972/how-to-merge-two-array-of-object-by-using-lodash | |
_.mixin({ | |
mergeByKey(arr1, arr2, key) { | |
const criteria = {}; | |
criteria[key] = null; | |
return _.map(arr1, (item) => { | |
criteria[key] = item[key]; | |
return _.merge(item, _.find(arr2, criteria)); | |
}); | |
}, | |
}); | |
// Example | |
const array1 = [ | |
{ a: 3, b: 3 }, | |
{ a: 5, b: 5 }, | |
]; | |
const array2 = [{ b: 3 }, { b: 4 }, { b: 5 }]; | |
console.log(_.mergeByKey(array2, array1, 'b')); | |
// => [ { b: 3, a: 3 }, { b: 4 }, { b: 5, a: 5 } ] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment