JS / Jquery - using variable in json selector

I need to use a variable when fetching data from a json source like this. Json is retrieved using jquery getJSON()



var beverage = fanta;
var beverage_price = data.prices.beverage;


Now beverage_price = 10

var beverage = sprite;
var beverage_price = data.prices.beverage;


Now beverage_price = 20

When I try to do it like in the examples, the script tries to find a record of drinks in prices.

Thank you so much!


source to share

2 answers

As VisioN mentioned in the comment data.prices

is an array, you need to access its first element with [0]

which contains prices{ "fanta":10, "sprite":20}

here is a working example: http://jsfiddle.net/2E8AH/

Or you can make the data.prices

object like below: (if under your control)

var data = {
    "prices" : 


and can be accessed without [0]

like this: http://jsfiddle.net/Y8KtT/1/



You can access it for example:

var beverage = 'fanta';
var beverage_price = data.prices[0][beverage];




All Articles