user3672855 user3672855 - 2 months ago 9
Javascript Question

Accessing JSON data using string

I have a text box in which the user enters some strings delimited by comma, and these strings will be split on the front end, and sent to the backend to get some data in the form of JSON.

Here's the catch, when I actually typed the key of the JSON like below, it works.

var price = fun.results.KO;


But, when I tried to use the value of the split list, it kept on giving me error;

list_of_key = ["KO", "OK", "NA"]
fun.results.list_of_key[1];


The error says Uncaught TypeError: Cannot read property '0' of undefined

Where is my mistake? How to fix this?

If this is Python it would have world.

Answer

You have to use [] notation for it to work like that.

fun.results[list_of_key[1]];