I'm doing a personal project where I try to recover JavaScript Objects through URL, a kind of RESTful service so I need to convert the routes of my URL in JSON routes to recover the object in question, I do this from the following way:
Turning from URL to JSON PATH :
var path = "/example/to/object";
path = path.slice(1).replace(/[\/|\]/g, ".");
This results in:
=> path = "example.to.object";
My object:
var obj = {
"username":"denyncrawford",
"example": {
"to": {
"object": {}
}
}
}
Now, the problem is that normally if I want to use a variable to locate the key of an object I use the following syntax obj[variable]
, but in this case using obj[path]
returns undefined
.
How could I solve it? o Is there a way ( better ) to do what I want?
Functional example:
var str = "/denyncrawford/img";
str = str
.slice(1)
.replace(/[\/|\]/g, ".");
str2 = str
.replace(/[\/|\]/g, "."); // Sin slice().
var obj = {
"username":"denyncrawford",
"denyncrawford": {
"img":"denyn.png"
}
}
console.log(str);
console.log(obj[str]);
console.log(obj[str2]);
Thank you very much!