1

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"

PSL
  • 123,204
  • 21
  • 253
  • 243
Nathan Leggatt
  • 398
  • 1
  • 6
  • 18
  • possible duplicate of [JavaScript object: access variable property by name as string](http://stackoverflow.com/questions/4255472/javascript-object-access-variable-property-by-name-as-string) - This has been answered so many times it's ridiculous. – Pointy Sep 26 '13 at 03:06
  • again, notice that my item is TWO levels deep. It would work with a simple [varname] if it were the next item in the object tree, BUT, I'm trying to go two levels deep via the imageType value – Nathan Leggatt Sep 26 '13 at 03:09
  • Well yes, but the answer still involves just applying that basic technique. – Pointy Sep 26 '13 at 13:17

1 Answers1

4

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");
Andy Jones
  • 6,205
  • 4
  • 31
  • 47
  • very close... here's the corrected code that appears to have worked: function traverse(obj, path) { var links = path.split("."); for (var x = 0; x < links.length; ++x) { obj = obj[links[x]]; } return obj; } – Nathan Leggatt Sep 26 '13 at 03:21