在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?

当前回答

除了前面所有的答案,如果你想知道我们将如何在未来使用计算属性名(ECMAScript 6)编写动态属性名,下面是如何:

var person = "John Doe";
var personId = "person_" + new Date().getTime();
var personIndex = {
    [ personId ]: person
//  ^ computed property name
};

personIndex[ personId ]; // "John Doe"

参考:理解ECMAScript 6 -尼古拉斯扎卡斯

其他回答

使用.(点)方法向现有对象添加属性时要小心。

(.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。因此,添加动态创建的属性的最佳方法是[括号]方法。

最简单和最方便的方法是。

var varFieldName = "good";
var ob = {};
Object.defineProperty(ob, varFieldName , { value: "Fresh Value" });

基于# abbeing答案!

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
}

这使用了新的计算属性语法和模板字面量。

是的,这是可能的。我已经实现了使用下面的实现。对于这个,我得到了一个数组作为响应,我想在对象中作为属性列表。

response = {
  "equityMonths": [
    {
      "id": 1,
      "month": "JANUARY",
      "isEligible": false
    },
    {
      "id": 2,
      "month": "FEBRUARY",
      "isEligible": true
    },
    {
      "id": 3,
      "month": "MARCH",
      "isEligible": false
    },
    {
      "id": 4,
      "month": "APRIL",
      "isEligible": true
    },
    {
      "id": 5,
      "month": "MAY",
      "isEligible": false
    },
    {
      "id": 6,
      "month": "JUNE",
      "isEligible": true
    },
    {
      "id": 7,
      "month": "JULY",
      "isEligible": true
    },
    {
      "id": 8,
      "month": "AUGUST",
      "isEligible": false
    },
    {
      "id": 9,
      "month": "SEPTEMBER",
      "isEligible": true
    },
    {
      "id": 10,
      "month": "OCTOBER",
      "isEligible": false
    },
    {
      "id": 11,
      "month": "NOVEMBER",
      "isEligible": true
    },
    {
      "id": 12,
      "month": "DECEMBER",
      "isEligible": false
    }
  ]
}

在这里,我想要equityMonths作为对象,Jan到Dec是键,isEligible作为值。为此,我们必须使用Object类的defineProperty()方法,该方法允许向对象中添加动态属性。

向对象动态添加属性的代码。

let equityMonth = new Object();

response.equityMonths.forEach(element => {
    Object.defineProperty(equityMonth, element['month'], {
       value: element['isEligible'],
       writable: true,
       enumerable: true,
       configurable: true
    });
});
console.log("DATA : " + JSON.stringify(equityMonth));

在上面的代码中,我们有一个equityMonths数组,我们已经将其转换为对象的属性。

输出:

DATA : {"JANUARY":false,"FEBRUARY":true,"MARCH":false,"APRIL":true,"MAY":false,"JUNE":true,"JULY":true,"AUGUST":false,"SEPTEMBER":true,"OCTOBER":false,"NOVEMBER":true,"DECEMBER":false}

您可以使用下面的一些选项动态添加属性:

在你的例子中:

var data = {
    'PropertyA': 1,
    'PropertyB': 2,
    'PropertyC': 3
};

你可以用下面两种方式定义一个带有动态值的属性:

data.key = value;

or

data['key'] = value;

甚至,如果你的键也是动态的,你可以使用Object类定义:

Object.defineProperty(data, key, withValue(value));

其中data是对象,key是存储键名的变量,value是存储值的变量。

我希望这能有所帮助!