Is it possible to add dynamically named properties to JavaScript object?

后端 未结 19 1472
攒了一身酷
攒了一身酷 2020-11-21 05:39

In JavaScript, I\'ve created an object like so:

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

Is it poss

19条回答
  •  盖世英雄少女心
    2020-11-21 06:11

    You can add properties dynamically using some of the options below:

    In you example:

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

    You can define a property with a dynamic value in the next two ways:

    data.key = value;
    

    or

    data['key'] = value;
    

    Even more..if your key is also dynamic you can define using the Object class with:

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

    where data is your object, key is the variable to store the key name and value is the variable to store the value.

    I hope this helps!

提交回复
热议问题