在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);

其他回答

下面是我解决这个问题的方法。

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"
}

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

在你的例子中:

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是存储值的变量。

我希望这能有所帮助!

只是对上面的答案的补充。您可以定义一个函数来封装下面提到的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

我正在寻找一个解决方案,我可以在对象声明中使用动态键名(不使用ES6功能,如…或[key]: value)

这是我想到的:

var obj = (obj = {}, obj[field] = 123, obj)

一开始看起来有点复杂,但其实很简单。我们使用逗号操作符在一行中运行三个命令:

Obj ={}:创建一个新对象并将其赋值给变量Obj Obj [field] = 123:向Obj添加计算属性名 Obj:使用Obj变量作为括号/逗号列表的结果

这种语法可以在函数形参中使用,而不需要显式声明obj变量:

//查看结果的test函数。 函数showObject(obj) { console.log (obj); } //动态字段名。 var field = "myDynamicField"; //调用动态对象的函数。 showObject((obj = {}, obj[field] = 123, obj)); / * 输出: { “myDynamicField”:真的 } * /

一些变化

“严格模式”解决方案:

上面的代码不能在严格模式下工作,因为没有声明变量“obj”。

// This gives the same result, but declares the global variable `this.obj`!
showObject( (this.obj = {}, obj[field] = 123, obj) );

在初始化器中使用计算属性名的ES2015代码:

// Works in most browsers, same result as the other functions.
showObject( {[field] = 123} );

这个解决方案适用于所有现代浏览器(但不适用于IE,如果我需要提及的话)

使用JSON.parse()的超级hack方式:

// Create a JSON string that is parsed instantly. Not recommended in most cases.
showObject( JSON.parse( '{"' + field +'":123}') );
// read: showObject( JSON.parse( '{"myDynamicfield":123}') );

键中允许有特殊字符

注意,还可以在计算属性名中使用空格和其他特殊字符(在JSON.parse中也是如此)。

var field = 'my dynamic field :)';
showObject( {[field] = 123} );
// result: { "my dynamic field :)": 123 }

这些字段不能使用点(obj.)访问。My dynamic field:)显然在语法上是无效的),但只能通过括号符号,即obj[' My dynamic field:)']返回123

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

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}