首页 文章

是否可以向JavaScript对象添加动态命名属性?

提问于
浏览
602

在JavaScript中,我创建了一个像这样的对象:

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?

15 回答

  • 989

    这就是我解决问题的方法 .

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

    生成以下对象:

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

    我知道这个帖子已经有几个答案了,但我还没有看到一个有多个属性且它们在一个数组中的答案 . 顺便提一下,这个解决方案适用于ES6 .

    为了说明,假设我们有一个名为person的数组,其中包含对象:

    let Person = [{id:1, Name: "John"}, {id:2, Name: "Susan"}, {id:3, Name: "Jet"}]
    

    因此,您可以添加具有相应值的属性 . 假设我们要添加 Language ,默认值为 EN .

    Person.map((obj)=>({...obj,['Language']:"EN"}))
    

    Person 数组现在会变成这样:

    Person = [{id:1, Name: "John", Language:"EN"}, 
    {id:2, Name: "Susan", Language:"EN"}, {id:3, Name: "Jet", Language:"EN"}]
    
  • 52

    当然 . 可以将其视为字典或关联数组 . 您可以随时添加它 .

  • 19

    最简单,最便携的方式是 .

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

    基于#abeing的答案!

  • 0

    是 .

    var data = {
        'PropertyA': 1,
        'PropertyB': 2,
        'PropertyC': 3
    };
    
    data["PropertyD"] = 4;
    
    // dialog box with 4 in it
    alert(data.PropertyD);
    alert(data["PropertyD"]);
    
  • 75

    ES6获胜!

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

    如果您记录 data ,您会得到:

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

    这使用了新的Computed Property语法和Template Literals .

  • 10

    Be careful 使用 .(dot) 方法向现有对象添加属性 .

    (.dot) 只有在事先使用 'key' 'key' 否则使用 [bracket] 方法时,才应使用向对象添加属性的方法 .

    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 }
    

    注意控制台日志末尾的 problem - 'key: 1999' 而不是 Property6: 6, Property7: 7,.........,Property1999: 1999 . 因此,添加动态创建的属性的最佳方法是[bracket]方法 .

  • 79

    除了之前的所有答案,如果您要使用计算属性名称(ECMAScript 6)在 Future 中编写动态属性名称,请按以下步骤操作:

    var person = "John Doe";
    var personId = "person_" + new Date().getTime();
    var personIndex = {
        [ personId ]: person
    //  ^ computed property name
    };
    
    personIndex[ personId ]; // "John Doe"
    

    参考:Understanding ECMAScript 6 - Nickolas Zakas

  • 5

    我知道问题得到了很好的回答,但我也找到了另一种添加新属性的方法,并希望与您分享:

    你可以使用函数 Object.defineProperty()

    发现于Mozilla Developer Network

    例:

    var o = {}; // Creates a new object
    
    // Example of an object property added with defineProperty with a data property descriptor
    Object.defineProperty(o, "a", {value : 37,
                                   writable : true,
                                   enumerable : true,
                                   configurable : true});
    // 'a' property exists in the o object and its value is 37
    
    // Example of an object property added with defineProperty with an accessor property descriptor
    var bValue;
    Object.defineProperty(o, "b", {get : function(){ return bValue; },
                                   set : function(newValue){ bValue = newValue; },
                                   enumerable : true,
                                   configurable : true});
    o.b = 38;
    // 'b' property exists in the o object and its value is 38
    // The value of o.b is now always identical to bValue, unless o.b is redefined
    
    // You cannot try to mix both :
    Object.defineProperty(o, "conflict", { value: 0x9f91102, 
                                           get: function() { return 0xdeadbeef; } });
    // throws a TypeError: value appears only in data descriptors, get appears only in accessor descriptors
    
  • 1

    只是上述abeing答案的补充 . 您可以定义一个函数来封装defineProperty的复杂性,如下所述 .

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

    参考:http://addyosmani.com/resources/essentialjsdesignpatterns/book/#constructorpatternjavascript

  • 0

    在这里,使用您的符号:

    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'
    
  • 2

    您可以使用以下某些选项动态添加属性:

    在你的例子中:

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

    您可以在接下来的两种方式中定义具有动态值的属性:

    data.key = value;
    

    要么

    data['key'] = value;
    

    更多..如果您的密钥也是动态的,您可以使用Object类定义:

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

    其中 data 是您的对象, key 是存储键名称的变量, value 是存储值的变量 .

    我希望这有帮助!

  • 15

    您只需使用点表示法即可添加任意数量的属性:

    var data = {
        var1:'somevalue'
    }
    data.newAttribute = 'newvalue'
    

    or

    data[newattribute] = somevalue
    

    用于动态密钥 .

  • 7

    从包含对象的动态字符串名称访问的好方法(例如object.subobject.property)

    function ReadValue(varname)
    {
        var v=varname.split(".");
        var o=window;
        if(!v.length)
            return undefined;
        for(var i=0;i<v.length-1;i++)
            o=o[v[i]];
        return o[v[v.length-1]];
    }
    
    function AssignValue(varname,value)
    {
        var v=varname.split(".");
        var o=window;
        if(!v.length)
            return;
        for(var i=0;i<v.length-1;i++)
            o=o[v[i]];
        o[v[v.length-1]]=value;
    }
    

    例:

    ReadValue("object.subobject.property");
    WriteValue("object.subobject.property",5);
    

    eval适用于读取值,但写入值有点困难 .

    更高级的版本(如果它们不存在则创建子类,并允许对象而不是全局变量)

    function ReadValue(varname,o=window)
    {
        if(typeof(varname)==="undefined" || typeof(o)==="undefined" || o===null)
            return undefined;
        var v=varname.split(".");
        if(!v.length)
            return undefined;
        for(var i=0;i<v.length-1;i++)
        {
            if(o[v[i]]===null || typeof(o[v[i]])==="undefined") 
                o[v[i]]={};
            o=o[v[i]];
        }
        if(typeof(o[v[v.length-1]])==="undefined")    
            return undefined;
        else    
            return o[v[v.length-1]];
    }
    
    function AssignValue(varname,value,o=window)
    {
        if(typeof(varname)==="undefined" || typeof(o)==="undefined" || o===null)
            return;
        var v=varname.split(".");
        if(!v.length)
            return;
        for(var i=0;i<v.length-1;i++)
        {
            if(o[v[i]]===null || typeof(o[v[i]])==="undefined")
                o[v[i]]={};
            o=o[v[i]];
        }
        o[v[v.length-1]]=value;
    }
    

    例:

    ReadValue("object.subobject.property",o);
    WriteValue("object.subobject.property",5,o);
    

    这与o.object.subobject.property相同

  • -11

    对的,这是可能的 . 假设:

    var data = {
        'PropertyA': 1,
        'PropertyB': 2,
        'PropertyC': 3
    };
    var propertyName = "someProperty";
    var propertyValue = "someValue";
    

    或者:

    data[propertyName] = propertyValue;
    

    要么

    eval("data." + propertyName + " = '" + propertyValue + "'");
    

    第一种方法是优选的 . 如果你使用用户提供的值,eval()有明显的安全问题,所以如果你能避免使用它就不要使用它,但值得知道它存在以及它能做什么 .

    您可以参考:

    alert(data.someProperty);
    

    要么

    data(data["someProperty"]);
    

    要么

    alert(data[propertyName]);
    

相关问题