Merge 2 arrays of objects using underscore.js

by Sahil Kashyap

JavaScript

/***************************************************/
/** Merge 2 arrays of objects using underscore.js **/
/***************************************************/

//arr2 will be merged into arr1, arr1 will be extended as needed.

var arr1 = [{name: "lang", value: "English"}, {name: "age", value: "18"}];
var arr2 = [{nameg : "childs", value: '5'}, {nameg: "lang", value: "German"}];

function mergeByProperty(arr1, arr2, prop,prop2) {
    _.each(arr2, function(arr2obj) {
        var arr1obj = _.find(arr1, function(arr1obj) {
            return arr1obj[prop] === arr2obj[prop2];
        });
         
        //If the object already exist extend it with the new values from arr2, otherwise just add the new object to arr1
        arr1obj ? _.extend(arr1obj, arr2obj) : null;
    });
}

mergeByProperty(arr1, arr2, 'name','nameg');

console.log(arr1);
//[{name: "lang", value: "German"}, {name: "age", value: "18"}, {name : "childs", value: '5'}]