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?)
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
You can try this:
var path = "hello.you";
eval("obj."+path);
                        If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With