JAVASCRIPT

[ Solved -10 Answers ] JAVASCRIPT – How to merge properties of two JavaScript objects dynamically

[ Solved -10 Answers ] JAVASCRIPT - How to merge properties of two JavaScript objects dynamically we need to be merge two (very simple) JavaScript objects

we need to be merge two (very simple) JavaScript objects at runtime.

For example :

Javascript Code
var obj1 = { food: 'pizza', car: 'ford' }
var obj2 = { animal: 'dog' }

obj1.merge(obj2);

//obj1 now has three properties: food, car, and animal

Here We do not need recursion and do not need to merge functions, just methods on flat objects.

ECMAScript (ES6) Standard Method

Javascript Code
/* For the case in question, we would do: */
Object.assign(obj1, obj2);

/** There's no limit to the number of objects we can merge.
 *  All objects get merged into the first object. 
 *  Only the object in the first argument is mutated and returned.
 *  Later properties overwrite earlier properties with the same name. */
const allRules = Object.assign({}, obj1, obj2, obj3, etc);

Method for ES5 and Earlier

javascript code
for (var attrname in obj2) 
{
 obj1[attrname] = obj2[attrname]; 
}

Note: This will simply add all attributes of obj2 to obj1 which might not be what you want if you still want to use the unmodified obj1.

Example:

Javascript Code
/**
 * Overwrites obj1's values with obj2's and adds obj2's if non existent in obj1
 * @param obj1
 * @param obj2
 * @returns obj3 a new object based on obj1 and obj2
 */
function merge_options(obj1,obj2){
    var obj3 = {};
    for (var attrname in obj1) { obj3[attrname] = obj1[attrname]; }
    for (var attrname in obj2) { obj3[attrname] = obj2[attrname]; }
    return obj3;
}

Here using JQuery extend method.
It can merge two objects together and all their properties.

From JQuery’s :

Javascript Code
var settings = { validate: false, limit: 5, name: "foo" };
var options = { validate: true, name: "bar" };
jQuery.extend(settings, options);
  • Now settings contains the merged settings and options objects

  • Extend a JavaScript object with the key/value pairs of another.
  • Here we can merge two objects into one new object:
Javascript Code
function extend(obj, src) {
    for (var key in src) {
        if (src.hasOwnProperty(key)) obj[key] = src[key];
    }
    return obj;
}

// example
var a = { foo: true }, b = { bar: false };
var c = extend(a, b);

console.log(c);
// { foo: true, bar: false }
  • This is typically useful when merging an options dict with the default settings in a function or a plugin.
  • If support for IE 8 is not required, we may use Object.keys for the same functionality instead:
Javascript Code
function extend(obj, src) {
    Object.keys(src).forEach(function(key) { obj[key] = src[key]; });
    return obj;
}

  • We are changed names from def and obj to target and source because they make more sense to me.
  • We have also included as simple isArray function.
READ  PHP - JAVASCRIPT - What is the difference between client-side and server-side programming

Note :We don’t like using the constructor property as it’s public and we might get an own property rather than the inherited one, so we changed the test for object.

  • If we test of an object, then for an array, what falls through should be a primitve.
  • There are a lot of assumptions here, we did implement a bit more checking to make sure getting what we expected.
Javascript Code
function isArray(o) {
  return Object.prototype.toString.call(o) == "[object Array]";
}

// Assumes that target and source are either objects (Object or Array) or undefined
// Since will be used to convert to JSON, just reference objects where possible
function mergeObjects(target, source) {

  var item, tItem, o, idx;

  // If either argument is undefined, return the other.
  // If both are undefined, return undefined.
  if (typeof source == 'undefined') {
    return source;
  } else if (typeof target == 'undefined') {
    return target;
  }
Javascript Code
// Assume both are objects and don't care about inherited properties
  for (var prop in source) {
    item = source[prop];

    if (typeof item == 'object' && item !== null) {

      if (isArray(item) && item.length) {

        // deal with arrays, will be either array of primitives or array of objects
        // If primitives
        if (typeof item[0] != 'object') {

          // if target doesn't have a similar property, just reference it
          tItem = target[prop];
          if (!tItem) {
            target[prop] = item;

          // Otherwise, copy only those members that don't exist on target
          } else {
Javascript Code
 // Create an index of items on target
            o = {};
            for (var i=0, iLen=tItem.length; i<iLen; i++) {
              o[tItem[i]] = true
            }

            // Do check, push missing
            for (var j=0, jLen=item.length; j<jLen; j++) {

              if ( !(item[j] in o) ) {
                tItem.push(item[j]);
              } 
            }
          }
        } else {
          // Deal with array of objects
          // Create index of objects in target object using ID property
          // Assume if target has same named property then it will be similar array
          idx = {};
          tItem = target[prop]
Javascript Code
 for (var k=0, kLen=tItem.length; k<kLen; k++) {
            idx[tItem[k].id] = tItem[k];
          }

          // Do updates
          for (var l=0, ll=item.length; l<ll; l++) {
            // If target doesn't have an equivalent, just add it
            if (!(item[l].id in idx)) {
              tItem.push(item[l]);
            } else {
              mergeObjects(idx[item[l].id], item[l]);
            }
          }  
        }
      } else {
Javascript Code
 // deal with object
        mergeObjects(target[prop],item);
      }

    } else {
      // item is a primitive, just copy it over
      target[prop] = item;
    }
  }
  return target;
}

  • Merge two objects, modifying the first.
Html Code
<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <title>jQuery.extend demo</title>
  <script src="https://code.jquery.com/jquery-1.10.2.js"></script>
</head>
<body>
 
<div id="log"></div>
 
<script>
var object1 = {
  apple: 0,
  banana: { weight: 52, price: 100 },
  cherry: 97
};
Html Code
var object2 = {
  banana: { price: 200 },
  durian: 100
};
 
// Merge object2 into object1
$.extend( object1, object2 );
 
// Assuming JSON.stringify - not available in IE<8
$( "#log" ).append( JSON.stringify( object1 ) );
</script>
 
</body>
</html>

READ  [Solved -14 Answers] JAVASCRIPT - How to convert a string to boolean in JavaScript

Using jQuery :

Javascript Code
// Merge options object into settings object
var settings = { validate: false, limit: 5, name: "foo" };
var options  = { validate: true, name: "bar" };
jQuery.extend(settings, options);

// Now the content of settings object is the following:
// { validate: true, limit: 5, name: "bar" }
  • The above code will mutate the object named settings.
  • If we want to create a new object without modifying either argument, use this:
Javascript Code
var defaults = { validate: false, limit: 5, name: "foo" };
var options = { validate: true, name: "bar" };

/* Merge defaults and options, without modifying defaults */
var settings = $.extend({}, defaults, options);

// The content of settings variable is now the following:
// {validate: true, limit: 5, name: "bar"}
// The 'defaults' and 'options' variables remained the same.

  • The Harmony ECMAScript 2015 (ES6) specifies Object.assign which will do this.
  • Object.assign(obj1, obj2);
    Current browser support is getting better, but if we are developing for browsers that don’t have support, we can use a polyfill.

Code

Javascript Code
/*
* Recursively merge properties of two objects 
*/
function MergeRecursive(obj1, obj2) {

  for (var p in obj2) {
    try {
      // Property in destination object set; update its value.
      if ( obj2[p].constructor==Object ) {
        obj1[p] = MergeRecursive(obj1[p], obj2[p]);

      } else {
        obj1[p] = obj2[p];

      }
Javascript Code

    } catch(e) {
      // Property in destination object not set; create it and set its value.
      obj1[p] = obj2[p];

    }
  }

  return obj1;
}

 example:

Javascript Code
o1 = {  a : 1,
        b : 2,
        c : {
          ca : 1,
          cb : 2,
          cc : {
            cca : 100,
            ccb : 200 } } };

o2 = {  a : 10,
        c : {
          ca : 10,
          cb : 20, 
          cc : {
            cca : 101,
            ccb : 202 } } };

o3 = MergeRecursive(o1, o2);
  • Produces object o3 like
Javascript Code
o3 = {  a : 10,
        b : 2,
        c : {
          ca : 10,
          cb : 20,
          cc : { 
            cca : 101,
            ccb : 202 } } };

  • Note that underscore.js’s extend-method does this in a one-liner:
Javascript Code
_.extend({name : 'moe'}, {age : 50});
=> {name : 'moe', age : 50}

  • Similar to jQuery extend(), you have the same function in AngularJS:
Javascript Code
// Merge the 'options' object into the 'settings' object
var settings = {validate: false, limit: 5, name: "foo"};
var options  = {validate: true, name: "bar"};
angular.extend(settings, options);

About the author

Venkatesan Prabu

Venkatesan Prabu

Wikitechy Founder, Author, International Speaker, and Job Consultant. My role as the CEO of Wikitechy, I help businesses build their next generation digital platforms and help with their product innovation and growth strategy. I'm a frequent speaker at tech conferences and events.

Add Comment

Click here to post a comment

X