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"

3
  • possible duplicate of JavaScript object: access variable property by name as string - This has been answered so many times it's ridiculous. Commented Sep 26, 2013 at 3: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 Commented Sep 26, 2013 at 3:09
  • Well yes, but the answer still involves just applying that basic technique. Commented Sep 26, 2013 at 13:17

1 Answer 1

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");
Sign up to request clarification or add additional context in comments.

1 Comment

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; }

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.