从两个单独的JavaScript对象合并属性的最佳方法是什么?

时间:2012-01-19 03:17:14

标签: javascript object cascade

我有一个javascript对象,我想用另一个对象的数据更新。我想从新对象中添加新内容,使用新对象更新旧内容,并在旧对象中保留任何不在新对象中的内容。 (示例在底部)

我尝试过各种各样的方法,但它们要么完全覆盖对象,要么不会在没有手动为对象中的对象写出循环等的情况下级联。

我还考虑了一个递归函数,它将迭代属性,检查它本身是否有另一个对象,以及它是否在更新对象时自行调用。 (没有写过,希望有更清洁的东西)

var obj1 = {id:1, name:"asdf", info:{first:3, second:{deeper:3} } };

var obj2 = {id:1, info:{first: 3, second:{deeper:5, new_deeper:6}, third:7}, new_info:7};

我想这样做,因此obj1相当于:

{id:1, name:"asdf", info:{first:3, second:{deeper:5, new_deeper:6}, third:7}, new_info:7};

提前谢谢!

1 个答案:

答案 0 :(得分:2)

我知道建议一个库并不总是一个很好的答案,但jQuery有一个$.extend方法,这对于这样做很有帮助。

// Add TRUE as the last parameter to copy nested objects
var newObj = $.extend(objectA, objectB, true);

如果您检查库,您可以获取该功能并将其用于您自己的东西。

http://code.jquery.com/jquery-1.7.1.js

jQuery.extend = function() {
    var options, name, src, copy, copyIsArray, clone,
        target = arguments[0] || {},
        i = 1,
        length = arguments.length,
        deep = false;

    // Handle a deep copy situation
    if ( typeof target === "boolean" ) {
        deep = target;
        target = arguments[1] || {};
        // skip the boolean and the target
        i = 2;
    }

    // Handle case when target is a string or something (possible in deep copy)
    if ( typeof target !== "object" && !jQuery.isFunction(target) ) {
        target = {};
    }

    // extend jQuery itself if only one argument is passed
    if ( length === i ) {
        target = this;
        --i;
    }

    for ( ; i < length; i++ ) {
        // Only deal with non-null/undefined values
        if ( (options = arguments[ i ]) != null ) {
            // Extend the base object
            for ( name in options ) {
                src = target[ name ];
                copy = options[ name ];

                // Prevent never-ending loop
                if ( target === copy ) {
                    continue;
                }

                // Recurse if we're merging plain objects or arrays
                if ( deep && copy && ( jQuery.isPlainObject(copy) || (copyIsArray = jQuery.isArray(copy)) ) ) {
                    if ( copyIsArray ) {
                        copyIsArray = false;
                        clone = src && jQuery.isArray(src) ? src : [];

                    } else {
                        clone = src && jQuery.isPlainObject(src) ? src : {};
                    }

                    // Never move original objects, clone them
                    target[ name ] = jQuery.extend( deep, clone, copy );

                // Don't bring in undefined values
                } else if ( copy !== undefined ) {
                    target[ name ] = copy;
                }
            }
        }
    }

    // Return the modified object
    return target;
};