在JavaScript中,我创建了一个这样的对象:
var data = {
'PropertyA': 1,
'PropertyB': 2,
'PropertyC': 3
};
如果直到运行时才确定属性名称,那么是否可以在初始创建该对象后向其添加更多属性?即。
var propName = 'Property' + someUserInput
//imagine someUserInput was 'Z', how can I now add a 'PropertyZ' property to
//my object?
我知道这篇文章已经有几个答案,但我还没有看到其中有多个属性,它们在一个数组中。顺便说一下,这个解决方案是针对ES6的。
举例来说,假设我们有一个名为person的数组,其中包含对象:
let Person = [{id:1, Name: "John"}, {id:2, Name: "Susan"}, {id:3, Name: "Jet"}]
因此,您可以添加具有相应值的属性。假设我们想要添加一个默认值为EN的Language。
Person.map((obj)=>({...obj,['Language']:"EN"}))
Person数组现在会变成这样:
Person = [{id:1, Name: "John", Language:"EN"},
{id:2, Name: "Susan", Language:"EN"}, {id:3, Name: "Jet", Language:"EN"}]
只是对上面的答案的补充。您可以定义一个函数来封装下面提到的defineProperty的复杂性。
var defineProp = function ( obj, key, value ){
var config = {
value: value,
writable: true,
enumerable: true,
configurable: true
};
Object.defineProperty( obj, key, config );
};
//Call the method to add properties to any object
defineProp( data, "PropertyA", 1 );
defineProp( data, "PropertyB", 2 );
defineProp( data, "PropertyC", 3 );
参考:http://addyosmani.com/resources/essentialjsdesignpatterns/book/ # constructorpatternjavascript
使用.(点)方法向现有对象添加属性时要小心。
(.dot)方法添加属性到对象应该只使用如果你事先知道'键'否则使用[括号]方法。
例子:
var data = {
'Property1': 1
};
// Two methods of adding a new property [ key (Property4), value (4) ] to the
// existing object (data)
data['Property2'] = 2; // bracket method
data.Property3 = 3; // dot method
console.log(data); // { Property1: 1, Property2: 2, Property3: 3 }
// But if 'key' of a property is unknown and will be found / calculated
// dynamically then use only [bracket] method not a dot method
var key;
for(var i = 4; i < 6; ++i) {
key = 'Property' + i; // Key - dynamically calculated
data[key] = i; // CORRECT !!!!
}
console.log(data);
// { Property1: 1, Property2: 2, Property3: 3, Property4: 4, Property5: 5 }
for(var i = 6; i < 2000; ++i) {
key = 'Property' + i; // Key - dynamically calculated
data.key = i; // WRONG !!!!!
}
console.log(data);
// { Property1: 1, Property2: 2, Property3: 3,
// Property4: 4, Property5: 5, key: 1999 }
注意控制台日志末尾的问题-
'key: 1999'而不是Property6: 6, Property7: 7,........., Property1999: 1999。因此,添加动态创建的属性的最佳方法是[括号]方法。