leafiy
5/18/2018 - 6:47 PM

object merge by property #js #object

none

/***************************************************/
/** 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 = [{name : "childs", value: '5'}, {name: "lang", value: "German"}];

function mergeByProperty(arr1, arr2, prop) {
    _.each(arr2, function(arr2obj) {
        var arr1obj = _.find(arr1, function(arr1obj) {
            return arr1obj[prop] === arr2obj[prop];
        });
         
        //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) : arr1.push(arr2obj);
    });
}

mergeByProperty(arr1, arr2, 'name');

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