I am working on a personal project (using node.js) where I need to get the route of the GET request, for example "/path/to/content"
, transform it into an Object and make it look like this:
{
"path": {
"to": {
"content":[...]
}
}
}
It seems to me that replacing with split()
could work, I tried in the following way:
const button = document.getElementsByClassName("me");
for (var i=0; i < button.length; i++) {
button[i].addEventListener("click", function(){
var str = "/denyncrawford/files/img"; //path de la solicitud
str = str.slice(1);
var obj= str.split("/");
document.querySelector("body").innerHTML += " <pre>"+JSON.stringify(obj, null, 2)+"</pre>"
});
}
p span {
background-color: #f0e4da
}
<p><b>PATH:</b><span>/denyncrawford/files/img</span></p>
<button class="me">Convertir</button>
And this returns an Array that contains the three strings:
[
"denyncrawford",
"files",
"img"
]
How could I make the array an object path like in the first example?:
{
"denyncrawford": {
"files": {
"img":[...]
}
}
}
Because using Object.assign()
results in the following way:
Object.assign({}, obj);
=>
{
0:"denyncrawford",
1:"files",
2:"img"
}
I hope you can help me, thank you!