且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

将多个属性添加到现有js对象

更新时间:2023-12-01 21:32:28

来自如何动态合并两个JavaScript对象的属性?

var obj2 = {name: 'don', gender: 'male'};
for (var attrname in myobject) { myobject[attrname] = obj2[attrname]; }

编辑

要有点儿更清楚如何扩展Object以使用此函数:

To be a bit clearer about how you could extend Object to use this function:

//Extend the protype so you can make calls on the instance
Object.prototype.merge = function(obj2) {
    for (var attrname in obj2) {
        this[attrname] = obj2[attrname];
    }
    //Returning this is optional and certainly up to your implementation.  
    //It allows for nice method chaining.
    return this;
};
//Append to the object constructor function so you can only make static calls
Object.merge2 = function(obj1, obj2) {
    for (var attrname in obj2) {
        obj1[attrname] = obj2[attrname];
    }
    //Returning obj1 is optional and certainly up to your implementation
    return obj1;
};

用法:

var myObject1 = { One: "One" };
myObject1.merge({ Two: "Two" }).merge({ Three: "Three" });
//myObject1 is { One: "One", Two: "Two", Three: "Three", merge: function }


var myObject2 = Object.merge2({ One: "One" }, { Two: "Two" });
Object.merge2(myObject2, { Three: "Three" });
//myObject2 is { One: "One", Two: "Two", Three: "Three" }

注意:您当然可以根据需要实施灵活的合并冲突策略。

Note: You certainly could implement a flexible merge conflict strategy depending on your needs.