Add multiple attributes to an existing js object

前端 未结 6 1030
不知归路
不知归路 2020-12-31 01:50

I want to add multiple attributes to an existing object with existing attributes. Is there a more concise way than one line per new attribute?

myObject.name         


        
6条回答
  •  悲&欢浪女
    2020-12-31 02:02

    From How can I merge properties of two JavaScript objects dynamically?

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

    EDIT

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

    Usage:

    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.

提交回复
热议问题