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}}
2

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Can you explain why this actually changes the variable a as well? jsfiddle.net/59s4a
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.

4 Comments

This seems pretty similar to Darin's. Is there a way to make it kick out a return instead of modifying the actual variable?
So, you don't want it modifying the original variables? You want a new object?
Yeah, I need it to be a new object.
Sure, updated the code and the JSbin to give you a clone instead and leave original in tact.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.