Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

175
Vistas
how to parse a string path, and get result like this?

input:

/home/ubuntu

output:

[
{"name":"/","path":"/"},
{"name":"home",path:"/home"},
{"name":"ubuntu",path:"/home/ubuntu"}
]

how to get like this?

about 4 years ago · Juan Pablo Isaza
2 Respuestas
Responde la pregunta

0

I guess this is what you need:

getTree = (path, nodes = []) => {
  // Split by levels
  const parts = path.split('/')
  // Remove last node from path and add to nodes array
  nodes.push({ name: parts.pop(), path })
  // Update path without last node (already added)
  path = parts.join('/')
  if (path.length) {
    // Recall method recursively if nodes left
    return getTree(path, nodes)
  } else {
    // Or add root node to array and return it
    nodes.push({ name: '/', path: '/' })
    return nodes
  }
}

Usage:

const path = '/root/user/home/ubuntu'
console.log(getTree(path))

Output:

[
  {name: 'ubuntu', path: '/root/user/home/ubuntu'}
  {name: 'home', path: '/root/user/home'}
  {name: 'user', path: '/root/user'}
  {name: 'root', path: '/root'}
  {name: '/', path: '/'}
]
about 4 years ago · Juan Pablo Isaza Denunciar

0

If i understood your question correctly, you could do something like this

By using Array.prototype.split() to split the path into parts, and setting the first argument (the base) as the home and the rest of the arguments as the resultant path

const string = 'home/ubuntu/test';
console.log(parse(string));
console.log(parse('home/'));
console.log(parse('/'));

function parse(str) {
    const obj = {};
    const strArr = str.split('/');

    obj['home'] = strArr[0] ? strArr[0] : '/';
    const path = strArr.slice(1, strArr.length).join('/');

    obj['path'] = path ? path : '/';
    return obj;
}

P.S if this is not what you meant please let me know in the comments

about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda