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

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

    Here's how I solved the problem.

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

    Generates the following object:

    {
      "someouter": {
        "someinner": {
          "someValue": 123
        }
      },
      "simpleString": "string"
    }
    

提交回复
热议问题