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]
)?
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]
)?
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"
if path = "foo.bar"
then you may write
var keys = path.split('.');
console.log(obj[keys[0]][keys[1]]);
just use the obj.foo.bar..that will work;