4

How can I merge two (or more) JS objects like this?

The result should contain all functions (like showUser and showOtherData) and events and requests-arrays should be merged as well.

var object1 = {
  events: {
    'app.activated': 'showUser'
  },
  requests: {
  },
  showUser: function() {
    console.log("es jhsod")
  },
};

var object2 = {
  events: {
    'app.destroyed': 'hideUser'
  },

  requests: {
    main: {
      url: 'http://example/api/main',
      data: {
        format: 'json'  
      }
    }
  },

  showOtherData: function() {
    console.log("foobar")
  },
};
James
  • 109,676
  • 31
  • 162
  • 175
Hedge
  • 16,142
  • 42
  • 141
  • 246
  • possible duplicate of [deep merge objects with AngularJS](http://stackoverflow.com/questions/17242927/deep-merge-objects-with-angularjs) –  Feb 26 '15 at 11:46
  • possible duplicate of [How can I merge properties of two JavaScript objects dynamically?](http://stackoverflow.com/questions/171251/how-can-i-merge-properties-of-two-javascript-objects-dynamically) – AeroX Feb 26 '15 at 11:46

2 Answers2

3

I know there are already some implementations, but this is so much fun to write recursive functions. Check this one more extend function for your problem. It also supports unlimited number of arguments:

function extend() {

    var result = {}, obj;

    for (var i = 0; i < arguments.length; i++) {
        obj = arguments[i];
        for (var key in obj) {
            if (Object.prototype.toString.call(obj[key]) === '[object Object]') {
                if (typeof result[key] === 'undefined') {
                    result[key] = {};
                }
                result[key] = extend(result[key], obj[key]);
            } 
            else {
                result[key] = obj[key];
            }
        }
    }
    return result;
}

console.log(extend(object1, object2, object3));

Demos: http://jsfiddle.net/zgbwtp4g/, http://jsfiddle.net/zgbwtp4g/1

dfsq
  • 191,768
  • 25
  • 236
  • 258
1

There is no easy way but there are various implementation online stemming from different libraries, i.e lodash merge or jquery extend. You can see the implementation of those and implement it yourself.

This seems to show a nice implementation: merge

skay-
  • 1,546
  • 3
  • 16
  • 26