将多个属性添加到现有js对象 [英] Add multiple attributes to an existing js object
问题描述
我想为具有现有属性的现有对象添加多个属性。每个新属性是否比一行更简洁?
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 = 'don';
myObject.gender = 'male';
MDN上的所有内容都显示了如何使用括号表示法创建新对象,但不显示现有对象: https://developer.mozilla.org/en-US/docs/JavaScript/Guide/ Working_with_Objects
Everything on MDN shows how to do new objects with bracket notation, but not existing objects: https://developer.mozilla.org/en-US/docs/JavaScript/Guide/Working_with_Objects
推荐答案
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.
这篇关于将多个属性添加到现有js对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!