0

I have a a function that takes a string like "obj.key.subkey.subsubkey":

function(obj, key) {
  return eval('obj.'+ key);
}

What would be a safe alternative to eval in this case or is eval fine? new Function won't work in this case AFAIK. Maybe split and loop then?

elclanrs
  • 92,861
  • 21
  • 134
  • 171

1 Answers1

1

I'm not sure you really need a function here. If you have the object and the key just use the key to return the property on the object.

obj[key]

If you must handle multiple keys:

function get(obj, key) {
  var keys = key.split(".");
  var tmp = obj;
  for (var x = 0; x < keys.length; x++){
     tmp = tmp[keys[x]];
  }
  return tmp;
}

Working Example: http://jsfiddle.net/H55ka/

Kevin Bowersox
  • 93,289
  • 19
  • 159
  • 189
  • I ended up doing it like this but same idea, just to be able to chain it: `return keys.map(function(k) { return tmp = tmp[k]; }).pop()` – elclanrs Feb 03 '13 at 11:32
  • @elclanrs Nice! But from what I have read .map is only supported in IE >=9. Just so your aware. https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Array/map – Kevin Bowersox Feb 03 '13 at 11:40
  • @elclanrs: Note though that any of these solutions will throw an error if any key in the "chain" does not exist in the object. – Felix Kling Feb 03 '13 at 11:42
  • This is basically for Node and ES5 so i'm good there. @FelixKling: Right, this is not an issue in my case because all the objects have the same keys but good to keep in mind. – elclanrs Feb 03 '13 at 11:54