Kevin Py Kevin Py - 23 days ago 7
Javascript Question

Merge 2 arrays of objects with different keys with lodash

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"
}
];

Answer

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>