Is it possible to define a dynamically named property using object literal in JavaScript?

后端 未结 7 1646
南旧
南旧 2021-01-17 16:05

Consider the following

var a = {foo: \"bar\"};

Equivalent to

var a = {};
a.foo = \"bar\";

Equivalent to

相关标签:
7条回答
  • 2021-01-17 16:38

    ES6 supports computed properties.

    // code from my original question now works in ES6 !
    let b = "foo";
    let a = { [b]: "bar" };
    
    a.foo; //=> "bar"
    

    Any expression can be used within the [] to define the property name

    let a = {
      [(xs => xs.join(''))(['f','o','o'])]: 'bar'
    };
    
    a.foo; //=> "bar"
    

    If you need to rely on this behavior in an ES5 world, you can lean on the very capable babel.js to transpile your ES6 code to ES5-compatible code.

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