JSFiddle - React, Tailwind, and code Playground

by Alagar Kamuthurai

HTML

<script src="http://underscorejs.org/underscore.js"></script>

JavaScript

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

var arr1 = [{id: "100", title:"CEO"}, {id: "101", title:"CFO"},{id: "102", title:"CAO"}];
var arr2 = [{id: "100", dynamicLevel:"New CEO"}, {id: "101", dynamicLevel:" NewCFO"}];


function mergeByID(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);
    });
}

mergeByID(arr1, arr2, 'id');

console.log(arr1);