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


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


source


if path = "foo.bar"

, then you can write



var keys = path.split('.');
console.log(obj[keys[0]][keys[1]]);

      

+1


source


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


source


just use obj.foo.bar..it will work;

-3


source







All Articles