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

后端 未结 6 1493
渐次进展
渐次进展 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 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!

提交回复
热议问题