4

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?)

curly_brackets
  • 5,225
  • 14
  • 57
  • 99

3 Answers3

4

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

mariozski
  • 1,114
  • 1
  • 7
  • 20
4

You can try this:

var path = "hello.you";
eval("obj."+path);
alt-ctrl-dev
  • 661
  • 1
  • 6
  • 21
1

You can't do that but you can write function that will traverse nested object

function get(object, path) {
   path = path.split('.');
   var step;
   while (step = path.shift()) {
       object = object[step];
   }
   return object;
}

get(obj, 'hello.you');
jcubic
  • 56,835
  • 46
  • 206
  • 357