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

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

    Just an addition to abeing's answer above. You can define a function to encapsulate the complexity of defineProperty as mentioned below.

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

    reference: http://addyosmani.com/resources/essentialjsdesignpatterns/book/#constructorpatternjavascript

提交回复
热议问题