Dynamic object keys

后端 未结 2 1438
既然无缘
既然无缘 2021-01-15 08:42

Im trying to create an dynamic object with dynamic keys eg:

var test = \"test\";
var obj = {
    test:\"bananas\"
}

But I get an error:

相关标签:
2条回答
  • 2021-01-15 09:20
    obj[test + "ing"] = "bananas";
    

    In relation to your edit:

    var test = "test";
    var obj = {};
    obj[test] = "bananas";
    

    or shorter:

    var obj={[test]:"bananas"};
    

    I normally wrap this in something like:

    Object.expander = function(name, value, obj)
    {
        obj = obj || {};
        obj[name] = value;
        return obj;
    };
    
    var obj = Object.expander(test, "bananas");
    
    0 讨论(0)
  • 2021-01-15 09:21

    you can't this way

    try this instead

       obj["testing"] = "bananas"
    
    0 讨论(0)
提交回复
热议问题