How to merge complex JS objects

javascript

Solution

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

Problem

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

Original source

Related problems