简体   繁体   English

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

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

I have a javascript object that I would like to update with data from another object. 我有一个javascript对象,我想用另一个对象的数据更新。 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: 我想这样做obj1相当于:

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

Thank you in advance! 先感谢您!

I know suggesting a library isn't always a great answer, but jQuery has an $.extend method that is killer for doing this. 我知道建议一个库并不总是一个很好的答案,但是jQuery有一个$.extend方法,这对于这样做$.extend

// 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 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.

相关问题 在 JavaScript 中,有一种优雅的方法可以合并两个对象并总结任何共同属性? - In JavaScript there an elegant way to merge two Objects and sum any common properties? 比较两个对象中选定属性的最佳方法是什么 - what's the best way to compare selected properties in two objects 根据属性匹配两个单独的Javascript对象 - Matching Two Separate Javascript Objects based on Properties 合并两个 JavaScript 对象和冲突的属性 - Merge two JavaScript Objects and conflicting properties 减少和合并对象集合的最佳方法是什么 - What is the best way to reduce and merge a collection of objects 查看数组是否具有两个对象的两个不同属性的值相同的最佳方法是什么? - What is the best way to see if an array has two objects with the same values for two distinct properties? 从对象数组中查找对象索引的最佳方法是什么 - javascript - What is the best way to find index of object from array of objects - javascript 如何确保链接两个单独的javascript对象的属性 - How to ensure properties of two separate javascript objects are linked 在Javascript中创建对象数组的最佳方法是什么? - What is the best way to create an array of objects in Javascript? 实例化许多JavaScript对象的最佳方法是什么? - What is the best way of instantiating many JavaScript objects?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM