簡體   English   中英

從兩個單獨的JavaScript對象合並屬性的最佳方法是什么?

[英]What is the best way to merge properties from two separate JavaScript objects?

我有一個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};

先感謝您!

我知道建議一個庫並不總是一個很好的答案,但是jQuery有一個$.extend方法,這對於這樣做$.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;
};

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM