Home > front end >  accesing JSON objects with dynamic keys
accesing JSON objects with dynamic keys

Time:12-22

I have a JSON array of objects in this format:

 arr = [ {"s1" : [1,2,3]}, 
         {"s2" : [4,5,6]} ];

The values I want to access in this array will be determined dynamically. For example, if my dynamic variable is var num = 2;, then I want to access the key s2. That is, I want the output to be [4,5,6] when my num variable is equal to 2.

I tried this:

var num_name = "s"   num;
var output = arr[num-1].num_name;

But it doesn't work. It only works when I put the actual key name.

CodePudding user response:

You don't want the to use the key with the name num_name, but the key with the name contained in the value of the variable num_name. Using the subscript ([]) operator will do the trick:

var output = arr[num-1][num_name];
  • Related