Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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"
    }
];
like image 221
Kevin Py Avatar asked Nov 15 '16 14:11

Kevin Py


2 Answers

_.map(people, function(p){
    return _.merge(
        p, 
        _.find(data, {number: p.id})
    )
})
like image 70
stasovlas Avatar answered Oct 11 '22 18:10

stasovlas


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>
like image 41
TimoStaudinger Avatar answered Oct 11 '22 18:10

TimoStaudinger