EN
JavaScript - merge array of objects by property value using Lodash library
1
answers
0
points
How can I merge two arrays of objects using lodash?
For example, I have arrays of objects containing two properties such as type and value:
// ONLINE-RUNNER:browser;
var array = [
{ type: 'A', value: '1' },
{ type: 'B', value: '2' },
];
var update = [
{ type: 'A', value: '3' },
{ type: 'C', value: '4' },
];
and I want to compare and merge them by the type field, so that the result would be like this:
var retult = [
{ type: 'A', value: '3' }, // updated value
{ type: 'B', value: '2' }, // unchanged value
{ type: 'C', value: '4' } // added value
]
How can I do that?
1 answer
0
points
Use _.unionBy() method.
From the documentation:
This method is like
_.unionexcept that it acceptsiterateewhich is invoked for each element of eacharraysto generate the criterion by which uniqueness is computed. Result values are chosen from the first array in which the value occurs.
Practical examples
1. This example uses lodash cdn to import the library.
// ONLINE-RUNNER:browser;
<!doctype html>
<html>
<head>
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.21/lodash.min.js"></script>
</head>
<body>
<script>
var array = [
{ type: 'A', value: '1' },
{ type: 'B', value: '2' },
];
var update = [
{ type: 'A', value: '3' },
{ type: 'C', value: '4' },
];
var result = _.unionBy(update, array, 'type');
console.log(JSON.stringify(result, null, 4));
</script>
</body>
</html>
2. Node.js solution:
var _ = require('lodash');
var array = [
{ type: 'A', value: '1' },
{ type: 'B', value: '2' },
];
var update = [
{ type: 'A', value: '3' },
{ type: 'C', value: '4' },
];
var result = _.unionBy(update, array, 'type');
console.log(result);
References
0 comments
Add comment