How do I interpolate a variable as a key in a JavaScript object?

后端 未结 6 1488
渐次进展
渐次进展 2020-12-01 07:22

How can I use the value of the variable a as a key to lookup a property? I want to be able to say: b[\"whatever\"] and have this return 20:

相关标签:
6条回答
  • 2020-12-01 07:56

    Try this:

    var a = "whatever";
    var c = "something";
    var b = {whatever : 20, something: 37};
    alert(b[a]); // Shows 20
    alert(b[c]); // Shows 37
    

    Here is the fiddle.

    Or if I understand from the below comments correctly, try this:

    var a = "whatever";
    var b = {a : 20};
    alert(b.a); // Shows 20
    
    0 讨论(0)
  • 2020-12-01 08:00

    This works in Firefox 39 and Chrome 44. Don't know about other browsers. Also it doesn't work in nodejs v0.12.7.

    var a = "whatever";
    var b = { [a]: 20 };
    console.log(b["whatever"]); // shows 20
    

    That is, to interpolate a variable, enclose it in brackets.

    I'm not sure if this is a part of any standard. Originally, I saw such syntax here: https://hacks.mozilla.org/2015/07/es6-in-depth-classes/ where the author defined:

    [functionThatReturnsPropertyName()] (args) { ... }
    

    I'm also not sure if you should use that syntax. It's not widely known. Other members on your team might not understand the code.

    0 讨论(0)
  • 2020-12-01 08:00

    To show all options, I want mention the CoffeeScript way of doing this, which is:

    var a = "whatever";
    var b = (
      obj = {},
      obj["" + a] = 20,
      obj
    );
    
    alert(b.whatever); // 20
    

    Although I prefer:

    var a = "whatever";
    var b = {};
    b[a] = 20;
    
    alert(b.whatever); // 20
    
    0 讨论(0)
  • 2020-12-01 08:02
    var a = "whatever";
    var b = {a : 20};
    b[a] = 37;
    alert(b["whatever"]); // 37
    

    'a' is a string with the value 'a'. a is a variable with the value 'whatever'.

    0 讨论(0)
  • 2020-12-01 08:07

    Great question. I had a time trying to figure this out with underscore but the answer couldn't be more simple:

    var a = "whatever";
    var b = {a : 20};
    
    var array = [a, b]
    var answer = _.object([[array]])// {whatever: {a:20}}//NOTICE THE DOUBLE SET OF BRACKETS AROUND [[array]]
    

    I hope this helps!

    0 讨论(0)
  • 2020-12-01 08:08
    var a = "whatever";
    var b = {};
    b[a] = 20;
    alert(b["whatever"]); // shows 20
    
    0 讨论(0)
提交回复
热议问题