Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Defining "path" to object key with a string [duplicate]

Is it possible to define a "path" to an object key?

For instance if you have an object:

var obj = {
    hello: {
        you: "you"
    }
}

I would like to select it like this:

var path = "hello.you";
obj[path]; //Should return "you"

(Doesn't work obviously, but is there a way?)

like image 700
curly_brackets Avatar asked Jan 13 '23 23:01

curly_brackets


2 Answers

Quick code, you probably should make it error proof ;-)

var obj = {
    hello: {
        you: "you"
    }
};

Object.prototype.getByPath = function (key) {
  var keys = key.split('.'),
      obj = this;

  for (var i = 0; i < keys.length; i++) {
      obj = obj[keys[i]];
  }

  return obj;
};

console.log(obj.getByPath('hello.you'));

And here you can test -> http://jsbin.com/ehayav/2/

mz

like image 134
mariozski Avatar answered Jan 19 '23 12:01

mariozski


You can try this:

var path = "hello.you";
eval("obj."+path);
like image 44
alt-ctrl-dev Avatar answered Jan 19 '23 10:01

alt-ctrl-dev