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

当前回答

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

(.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 obj = {

};
var field = "someouter.someinner.someValue";
var value = 123;

function _addField( obj, field, value )
{
    // split the field into tokens
    var tokens = field.split( '.' );

    // if there's more than one token, this field is an object
    if( tokens.length > 1 )
    {
        var subObj = tokens[0];

        // define the object
        if( obj[ subObj ] !== undefined ) obj[ subObj ] = {};

        // call addfield again on the embedded object
        var firstDot = field.indexOf( '.' );
        _addField( obj[ subObj ], field.substr( firstDot + 1 ), value );

    }
    else
    {
        // no embedded objects, just field assignment
        obj[ field ] = value;
    }
}

_addField( obj, field, value );
_addField(obj, 'simpleString', 'string');

console.log( JSON.stringify( obj, null, 2 ) );

生成以下对象:

{
  "someouter": {
    "someinner": {
      "someValue": 123
    }
  },
  "simpleString": "string"
}

Yes.

Var数据= { “PropertyA”:1、 “PropertyB”:2 “PropertyC”:3 }; data["PropertyD"] = 4; //对话框中包含4 警报(data.PropertyD); 警报(数据(“PropertyD”));

ES6引入了计算属性名,它允许你这样做

let a = 'key'
let myObj = {[a]: 10};
// output will be {key:10}

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

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}

如果在运行时添加混合的新属性,它会很有用:

data = { ...data, newPropery: value}

然而,展开运算符使用浅复制,但这里我们将数据赋给自身,因此不会丢失任何数据