I use Backbone/lodash for a project, and I wish merge 2 arrays of objects according to a specific value. With this example below, the merge is based on the same value with 2 different key (id and number).
Example
var people = [
{
id: "1",
name: "John"
},
{
id: "2",
name: "Jane"
}
];
var data = [
{
number: "2",
role: "Designer"
},
{
number: "1",
role: "Developer"
}
];
// Outpout
var merge = [
{
id: "1",
number: "1",
name: "John",
role: "Developer"
},
{
id: "2",
number: "2",
name: "Jane",
role: "Designer"
}
];
_.map(people, function(p){
return _.merge(
p,
_.find(data, {number: p.id})
)
})
I'm not aware of a lodash function that fulfills exactly this use case. However, your goal can be achieved with plain JavaScript and the lodash helpers _.assign()
and _.values()
pretty well:
var people = [{id: "1", name: "John"}, {id: "2", name: "Jane"}];
var data = [{number: "2", role: "Designer"}, {number: "1", role: "Developer"}];
var resultObj = {};
people.forEach(function(item) {
resultObj[item.id] = item;
});
data.forEach(function(item) {
resultObj[item.number] = _.assign({}, resultObj[item.number], item);
});
var result = _.values(resultObj);
console.log(result);
<script src='https://cdn.jsdelivr.net/lodash/4.17.1/lodash.min.js'></script>
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