在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?
一个完美简单的方法
var data = {
'PropertyA': 1,
'PropertyB': 2,
'PropertyC': 3
};
var newProperty = 'getThisFromUser';
data[newProperty] = 4;
console.log(data);
如果您想将它应用于数据数组(ES6/TS版本)
const data = [
{ 'PropertyA': 1, 'PropertyB': 2, 'PropertyC': 3 },
{ 'PropertyA': 11, 'PropertyB': 22, 'PropertyC': 33 }
];
const newProperty = 'getThisFromUser';
data.map( (d) => d[newProperty] = 4 );
console.log(data);
ES6为胜利而战!
const b = 'B';
const c = 'C';
const data = {
a: true,
[b]: true, // dynamic property
[`interpolated-${c}`]: true, // dynamic property + interpolation
[`${b}-${c}`]: true
}
如果你记录数据,你会得到这个:
{
a: true,
B: true,
interpolated-C: true,
B-C: true
}
这使用了新的计算属性语法和模板字面量。
我知道这篇文章已经有几个答案,但我还没有看到其中有多个属性,它们在一个数组中。顺便说一下,这个解决方案是针对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"}]