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

后端 未结 19 1519
攒了一身酷
攒了一身酷 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:22

    A perfect easy way

    var data = {
        'PropertyA': 1,
        'PropertyB': 2,
        'PropertyC': 3
    };
    
    var newProperty = 'getThisFromUser';
    data[newProperty] = 4;
    
    console.log(data);
    

    If you want to apply it on an array of data (ES6/TS version)

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

提交回复
热议问题