Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

184
Visualizações
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 Respostas
Responde à pergunta

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 Relatório

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda