Javascript - get path to object object
I have the following object
var obj = {};
obj.foo = {};
obj.foo.bar = "I want this";
given "path" "foo.bar"
as string, how do I get obj.foo.bar
(or obj[foo][bar]
)?
+1
Thorben Bochenek
source
to share
4 answers
Here's the way:
function getKey(key, obj) {
return key.split('.').reduce(function(a,b){
return a && a[b];
}, obj);
}
getKey('foo.bar', obj); //=> "I want this"
+7
elclanrs
source
to share
if path = "foo.bar"
, then you can write
var keys = path.split('.');
console.log(obj[keys[0]][keys[1]]);
+1
fcalderan
source
to share
Another way:
function resolve(root, path){
try {
return (new Function(
'root', 'return root.' + path + ';'
))(root);
} catch (e) {}
}
resolve(obj, 'foo.bar'); // "I want this"
More on this: fooobar.com/questions/4051 / ...
-1
leaf
source
to share
just use obj.foo.bar..it will work;
-3
Clover wu
source
to share