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

时间:2013-05-07 19:46:41

标签: javascript oop object

我想为具有现有属性的现有对象添加多个属性。每个新属性是否比一行更简洁?

myObject.name = 'don';
myObject.gender = 'male';

MDN上的所有内容都展示了如何使用括号表示法创建新对象,但不显示现有对象:https://developer.mozilla.org/en-US/docs/JavaScript/Guide/Working_with_Objects

6 个答案:

答案 0 :(得分:14)

在ES6 / ES2015中,您可以使用Object.assign方法

let obj = {key1: true};
console.log('old obj: ', obj);
let newObj = {key2: false, key3: false};

Object.assign(obj, newObj);
console.log('modified obj: ', obj);

答案 1 :(得分:6)

来自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]; }

修改

要更清楚地了解如何扩展Object以使用此功能:

//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" }

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

答案 2 :(得分:4)

有时我会这样做:

var props = {
   name : 'don',
   gender : 'male',
   age : 12,
   other : false
};
for(var p in props) myObject[p] = props[p];

答案 3 :(得分:3)

使用jQuery库

jQuery.extend(myObject, { name : 'don', gender : 'male' });

答案 4 :(得分:3)

在ECMAscript 5中,您可以使我们defineProperties

Object.defineProperties(myobject, {  
  name: {  
    value: 'don' 
  },  
  gender: {  
    value: 'male' 
  }  
});

答案 5 :(得分:1)

我不确定这是否有帮助,但是有一个窍门:

let obj = {a: 1, b: 2};
obj = {...obj, b: 3, c: 4};
console.log(obj); // {a: 1, b: 3, c: 4}

您可以尝试以某种方式使用此方法...通常,这是使用js解构方法添加或覆盖对象属性的单一衬里。