6

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,491
  • 15
  • 58
  • 102

3 Answers3

5

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,134
  • 1
  • 7
  • 20
4

You can try this:

var path = "hello.you";
eval("obj."+path);
alt-ctrl-dev
  • 689
  • 1
  • 6
  • 21
  • 3
    This will obviously totally fail if you have properties with "non-safe" characters. For instance you won't be able to access obj['super-mega']. – BlaM Jun 01 '15 at 13:49
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
  • 61,973
  • 54
  • 229
  • 402