Convert path (String) to object

2

I need a function that converts:

"/home/username/Documentos/app.txt"

for an object:

{
  "home": {
    "username":{
    "Documentos":
     "app.txt":{}
    }
  }
}

'

I was thinking of breaking the string by "/", but I did not find a way to put the indexes inside one another.

    
asked by anonymous 18.04.2017 / 08:10

1 answer

3

Use a split to "break" this String and then a loop that creates an object.

It could look like this:

var string = "/home/username/Documentos/app.txt";
var props = string.split('/').filter(Boolean); // para limpar e tirar o primeiro elemento
var prop; // a propriedade que vamos iterar
var obj = {}; // o objeto final
var temp = obj; // o ponteiro que vamos mudando para criar sub-objetos
while (prop = props.shift()) {
  temp[prop] = {};
  temp = temp[prop];
}
console.log(obj);

A more compact version with ES2015 could be:

function objectify(str) {
  const obj = {}, props = str.split('/').filter(Boolean)
  let prop, temp = obj;
  while (prop = props.shift()) temp = temp[prop] = {};
  return obj;
}
console.log(objectify("/home/username/Documentos/app.txt"));
    
18.04.2017 / 08:21