7

I have the following object

var obj = {};
obj.foo = {};
obj.foo.bar = "I want this";

given the "path" "foo.bar" as a string, how do I retrieve obj.foo.bar (or obj[foo][bar])?

Thorben Croisé
  • 12,407
  • 8
  • 39
  • 50

3 Answers3

17

Here's a way:

function getKey(key, obj) {
  return key.split('.').reduce(function(a,b){
    return a && a[b];
  }, obj);
}

getKey('foo.bar', obj); //=> "I want this"
elclanrs
  • 92,861
  • 21
  • 134
  • 171
  • 1
    Nice idea! Just one thing: If one property in the "path" is undefined this will throw a TypeError. I suggest you improve this by changing `return a[b]` to `return a && a[b]`. This way in that situation getKey returns `undefined`, which feels better – Thorben Croisé Sep 19 '13 at 10:29
  • @Tobo: Try it with a non-existent key, it should just return `undefined` as-is. – elclanrs Sep 19 '13 at 10:31
  • Oh I see if you input two in a row that are non-existent it will throw an error. Edited. – elclanrs Sep 19 '13 at 10:34
0

if path = "foo.bar" then you may write

var keys = path.split('.');
console.log(obj[keys[0]][keys[1]]);
Fabrizio Calderan
  • 120,726
  • 26
  • 164
  • 177
-4

just use the obj.foo.bar..that will work;

Clover Wu
  • 29
  • 4