Defining an "path" to an object using a string

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

For example, if you have 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 explicitly, but is there a way?)

+4
source share
3 answers

You can try the following:

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

Fast code, probably you should do this with an error; -)

 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 check → http://jsbin.com/ehayav/2/

M.Z.

+4
source

You cannot do this, but you can write a function that will traverse the nested object

 function get(object, path) { path = path.split('.'); var step; while (step = path.shift()) { object = object[step]; } return object; } get(obj, 'hello.you'); 
+1
source

Source: https://habr.com/ru/post/1468925/


All Articles