Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript - retrieve object property path [duplicate]

Tags:

javascript

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])?

like image 800
Thorben Croisé Avatar asked Jul 21 '26 06:07

Thorben Croisé


1 Answers

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"
like image 117
elclanrs Avatar answered Jul 23 '26 18:07

elclanrs