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,027
  • 1
  • 9
  • 11

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
  • 138,460
  • 30
  • 271
  • 271
1

Use square bracket syntax:

places[place][info]

Rick Viscomi
  • 7,253
  • 3
  • 34
  • 48