Convert URL to Object (JavaScript)

2

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!

    
asked by Dєηyη Crawford 27.12.2018 в 17:49
source

2 answers

4

JSON functions only work with strings that follow the JSON structure, they do not understand how to convert a route. You have to build the object yourself, split was a good starting point, here an example:

var path = "/denyncrawford/files/img";

var obj = path
  .split('/')
  .filter(x => !!x)
  .reverse()
  .reduce((prev, current) => {
      return Object.keys(prev).length
        ? { [current]: prev }
        : { [current]: [] };
  }, {});
  
 console.log(obj);
    
answered by 27.12.2018 / 18:09
source
1

You can create a recursive function that is responsible for doing the job:

function urlToObject(url,value,target) {
  const param=url.shift();
  target= target || {};
  if (url.length === 0) {
    //caso base
    target[param]=value;
    
  } else {
    if (target[param] == null) {
      target[param]=urlToObject(url,value,{});
    } else {
      target[param]=urlToObject(url,value,target[param]);
    }
  }
  return target;
}

const URL='aplicacion/datos/img';
const URL2='aplicacion/datos/json';
let obj=urlToObject(URL.split('/'),true);

console.log(obj);
obj=urlToObject(URL2.split('/'),1,obj);
console.log(obj);

This would allow you to accumulate data in the same parent object (or not) depending on whether you pass it as a third parameter. The second parameter would be the final value to assign and the first parameter would be the result of splitting the URL.

    
answered by 27.12.2018 в 18:17