0

I am trying to populate a JSON object by automatically setting the keys for an JSON object based on the string value of another array. For example,

var test = ["a","b"]
{test[0]:"A"}

enter image description here

However, I get a Syntax error when I do this, if I manually set the value as the string as shown in the third line {"a":"A"} this issue does not happen. I've checked that test[0] does indeed print out "a" and its datatype is a string. Is there any reason why this might be happening?

arieljannai
  • 2,124
  • 3
  • 19
  • 39
ROBOTPWNS
  • 4,299
  • 6
  • 23
  • 36
  • Have you tried `{test:["A"]}`? – Get Off My Lawn Jun 01 '18 at 16:11
  • `{[test[0]]:"A"}` results in `{a: "a"}` - surround your key in brackets, else its trying to write the key as `test[0]` – tymeJV Jun 01 '18 at 16:11
  • [There is no such thing as a "JSON Object"](http://benalman.com/news/2010/03/theres-no-such-thing-as-a-json/) ... what you have is an object literal. That has nothing to do with JSON. – Felix Kling Jun 01 '18 at 16:12
  • you are looking for [computed property names](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Object_initializer#Computed_property_names). – Nina Scholz Jun 01 '18 at 16:12
  • *"Is there any reason why this might be happening?"* Yes, `x[y]` is simply not valid syntax in place of the key in an object literal. – Felix Kling Jun 01 '18 at 16:15

1 Answers1

2

Try the following:

    var test = ["a","b"]
    var obj = {
        [test[0]]:"A"
    };
    console.log(obj);
amrender singh
  • 7,949
  • 3
  • 22
  • 28
  • Thanks, this solution works, could you explain why the brackets around test[0] is necessary in this case? – ROBOTPWNS Jun 01 '18 at 16:15
  • It is used for computed property names . For reference : https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Object_initializer#Computed_property_names – amrender singh Jun 01 '18 at 16:23