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

2
  • I haven't seen any ready made method, but you can write one easily Commented Mar 13, 2013 at 9:43
  • If you are sure in path then you can use eval("obj." + path);. Commented Mar 13, 2013 at 9:48

3 Answers 3

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

Sign up to request clarification or add additional context in comments.

Comments

4

You can try this:

var path = "hello.you";
eval("obj."+path);

1 Comment

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'].
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');

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.