Convert path (String) to object

Asked

Viewed 91 times

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 the "/", but I couldn’t find a way to put the contents inside each other.

1 answer

3


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

It could be 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"));

  • 1

    This was really my logic, I just wasn’t able to understand my own logic. I really liked the ES6 version very much thank you!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.