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")
  },
};
2

2 Answers 2

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

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

1 Comment

That is an awesome function. Thank you very much :)
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

Comments

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.