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

后端 未结 7 1645
南旧
南旧 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:17

    To answer your question, this is the only way that I know of. It uses eval. But beware, eval is evil!

    var b = "foo";
    var a = eval('({ ' + b + ': ' + '"bar"' + ' })');
    

    This is an ugly solution. To play it safe you should not rely on this. Don't use it!

    0 讨论(0)
  • 2021-01-17 16:19

    As others have said, no, there's currently no syntax for interpolated key strings in object literals in CoffeeScript; but it seems at some point this feature existed! In these GitHub issues there's some discussion about it: #786 and #1731.

    It's implemented in Coco and LiveScript as:

    b = 'foo'
    a = {"#{b}": 'baz'}
    
    # Or..
    a = {(b): 'bar'}
    
    0 讨论(0)
  • 2021-01-17 16:20

    JavaScript

    var a, b;
    (a = {})[b = 'foo'] = 'bar';
    

    CoffeeScript

    (a = {})[b = 'foo'] = 'bar'
    
    0 讨论(0)
  • 2021-01-17 16:26

    No.

    There is no way to do it using object literal notation.


    UPDATE: According to the ECMAScript standard 6.0 you are now able to do the following:

    var b = 'foo';
    var a = { [b]: 'bar' };
    
    console.log( a.foo );  // "bar"
    

    However, this solution won't work in old browsers, which do not support ES6.

    0 讨论(0)
  • 2021-01-17 16:26

    As of CoffeeScript version 1.9.1 this works:

    b = "foo"
    a = "#{b}": "bar"
    

    It compiles to:

    var a, b, obj;
    
    b = "foo";
    
    a = (
      obj = {},
      obj["" + b] = "bar",
      obj
    );
    

    Try it.

    0 讨论(0)
  • 2021-01-17 16:32

    JSON parse allows you to convert a JSON string into an object:

    JSON.parse('{"'+dynamicProperty+'":"bar"}');
    

    This is not exactly an object litteral, but if your objective is to enter your property name as a variable it works.

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