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

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

    0 讨论(0)
  • 2020-11-21 06:07

    ES6 for the win!

    const b = 'b';
    const c = 'c';
    
    const data = {
        a: true,
        [b]: true, // dynamic property
        [`interpolated-${c}`]: true, // dynamic property + interpolation
        [`${b}-${c}`]: true
    }
    

    If you log data you get this:

    {
      a: true,
      b: true,
      interpolated-c: true,
      b-c: true
    }
    

    This makes use of the new Computed Property syntax and Template Literals.

    0 讨论(0)
  • 2020-11-21 06:08

    Here, using your notation:

    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?
    data[propName] = 'Some New Property value'
    
    0 讨论(0)
  • 2020-11-21 06:09

    The simplest and most portable way is.

    var varFieldName = "good";
    var ob = {};
    Object.defineProperty(ob, varFieldName , { value: "Fresh Value" });
    

    Based on #abeing answer!

    0 讨论(0)
  • 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!

    0 讨论(0)
  • 2020-11-21 06:12

    Be careful while adding a property to the existing object using .(dot) method.

    (.dot) method of adding a property to the object should only be used if you know the 'key' beforehand otherwise use the [bracket] method.

    Example:

       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 }

    Note the problem in the end of console log - 'key: 1999' instead of Property6: 6, Property7: 7,.........,Property1999: 1999. So the best way of adding dynamically created property is the [bracket] method.

    0 讨论(0)
提交回复
热议问题