1

I have two objects:

{'1': {'a': 1, 'b': 2, 'c': 3}}, {'1': {'d': 4, 'e': 5, 'f': 6}, '2': {'g': 7}}.

Is there a function in native javascript (underscore is also being used in the project) where I can put in both objects and get this out?

{'1': {'a': 1, 'b': 2, 'c': 3, 'd': 4, 'e': 5, 'f': 6}, '2': {'g': 7}}
m0ngr31
  • 791
  • 13
  • 29

2 Answers2

3

I am afraid that there isn't such native function built-in javascript. But you could always try writing your own recursive function that would do the job:

function merge(a, b) {
    for (var key in b) {
        try {
            if (b[key].constructor === Object) {
                a[key] = merge(a[key], b[key]);
            } else {
                a[key] = b[key];
            }
        } catch(e) {
            a[key] = b[key];
        }
    }
    return a;
}

which can be used like this:

var a = { '1': { 'a': 1, 'b': 2, 'c': 3 } };
var b = { '1': { 'd': 4, 'e': 5, 'f': 6}, '2': {'g': 7} };

var result = merge(a, b);

and the result would be:

{"1":{"a":1,"b":2,"c":3,"d":4,"e":5,"f":6},"2":{"g":7}} 

as this jsfiddle illustrates.

Darin Dimitrov
  • 1,023,142
  • 271
  • 3,287
  • 2,928
1

[updated] You could use the following for merging without affecting the original objects:

var isObject = function(o) { return Object.prototype.toString.call(o) == '[object Object]'; };
var isArray = function(o) { return Object.prototype.toString.call(o) == '[object Array]'; };

function extend(a, b) {
  for (var prop in b) {
    if (isObject(b[prop])) {
      extend(a[prop]||(a[prop] = {}), b[prop]);
    }
    else if (isArray(b[prop])) {
      a[prop] = (a[prop]||[]).concat(b[prop]);
    }
    else {
      a[prop] = b[prop];
    }
  }
  return a;
}

function merge(dest, source) {
  var obj = extend({}, dest),
      sources = arguments.length > 2 ? [].slice.call(arguments,1) : [source];

  sources.forEach(function(source) {
    extend(obj, source);
  });

  return obj;
}

See working JSBin.

This updated version should allow you to merge more than one object and returns a copy of the merged objects, leaving the originals in place.

David Atchley
  • 1,204
  • 8
  • 10