1

If I have a function like this:

var get = function(place, info){
    return places.place.info;
}

and JSON like this:

var places = {
    "london":{
        "distance":50,
        "time":100
    }
}

How can I make the function get return the correct value if I use the following? At the moment it's taking it completely literally:

get("london", "time");
user2036108
  • 1,227
  • 1
  • 10
  • 12

2 Answers2

2

You should use square brackets notation:

var get = function(place, info){
    return places[place][info];
};

I'd also add some fool proof check, e.g.:

var get = function(place, info){
    return places[place] !== undefined
        && places[place][info];
};
VisioN
  • 143,310
  • 32
  • 282
  • 281
1

Use square bracket syntax:

places[place][info]

Rick Viscomi
  • 8,180
  • 4
  • 35
  • 50