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

问题描述 投票:13回答:6

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

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

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

javascript oop object
6个回答
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" }

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


17
投票

在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);

4
投票

有时我会这样做:

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

3
投票

使用jQuery库

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

3
投票

在ECMAscript 5中,你可以让我们成为defineProperties

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

1
投票

我不确定这是否有用,但有一个诀窍:

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

您可以尝试以某种方式使用它...通常,这是使用js destructuring方法添加或覆盖对象属性的单个衬垫。

© www.soinside.com 2019 - 2024. All rights reserved.