Nathan Leggatt
Nathan Leggatt

Reputation: 450

Accessing an objects property via a variable in Javascript

I have an object in Javascript. For example...:

vehicle.image.jpg.large = "mylargejpg.jpg";

or

vehicle.image.jpg.small = "mysmalljpg.jpg";

I then have a variable

var imageType = "jpg.small";

How can I dynamically return the value of that object using the "imageType" variable??

IE: vehicle.image\imageType; or whatever would return "mysmalljpg.jpg"

Upvotes: 1

Views: 91

Answers (1)

Andy Jones
Andy Jones

Reputation: 6275

You want to traverse your object...

// Takes an object and a path to some element and traverses the object
function traverse(obj, path) {
  // split the path into pieces 
  var links = path.split(".");

  // traverse the object - one level at a time 
  for (var x = 0; x < links.length; ++x) 
    obj = obj[links[x]];

  return obj;
}

traverse(vehicle.image, "jpg.small");

Upvotes: 4

Related Questions