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

发布于 2024-12-28 04:08:44 字数 604 浏览 3 评论 0原文

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

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

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

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

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

我想做所以 obj1 相当于:

{id:1, name:"asdf", info:{first:3, secondary:{deeper:5, new_deeper:6},third:7}, new_info:7};< /code>

预先感谢您!

I have a javascript object that I would like to update with data from another object. I want to add new things from the new object, update old things using the new object and leave alone anything in the old object that is not in the new object. (Example at the bottom)

I have tried various ways but they either overwrite the object completely or they do not cascade without manually writing out loops for objects in objects in objects, etc.

I have also thought about a recursive function that will iterate over the properties, check if it has another object inside itself and if it does call itself all while updating the object. (have not written it, in hopes of something cleaner)

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};

I would like to make it so obj1 be equivalent to:

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

Thank you in advance!

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

∝单色的世界 2025-01-04 04:08:44

我知道建议使用库并不总是一个好的答案,但是 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;
};

I know suggesting a library isn't always a great answer, but jQuery has an $.extend method that is killer for doing this.

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

If you check the library you could grab just that functionality and use it for your own stuff.

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;
};
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文