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

197
Visualizações
How to get path_name in recursive funciton javascript?

I created recursive function for listing all files and folder,I am listing fine but I need path name also how to append please help me.

const treeData = [
  {
    name: "root",
    children: [
      { name: "src", children: [{ name: "index.html" }] },
      { name: "public", children: [] },
    ],
  },
];

const RecursiveTree = (data) => {
  data.map((item) => {
    console.log(item.name);
    if (item.children) {
      RecursiveTree(item.children);
    }
  });
};

RecursiveTree(treeData);

How to get with pathname Expected result

root
root/src
root/src/index.html
about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

You can add an optional path='' argument, start empty, and then pass itself the current path :

const treeData = [{
  name: 'root',
  children : [{
    name: 'src',
    children: [{
      name: 'index.html'
    }]
  }, {
    name: 'public',
    children: []
  }]
}];

const RecursiveTree = (data, path='') => {
  data.forEach((item) => {
    const currentPath = path + "/" + item.name
    console.log(currentPath )
    if (item.children) {
      RecursiveTree(item.children, currentPath)
    }
  })
}

RecursiveTree(treeData)

about 4 years ago · Juan Pablo Isaza Relatório

0

To append a node name to the previous result, you have to somehow pas the nested structure. One way to do this would be through the function parameters. In the solution below I'll pass the current path as an array.

const treeData = [
  {
    name: "root",
    children: [
      { name: "src", children: [{ name: "index.html" }] },
      { name: "public", children: [] },
    ],
  },
];

function recursiveTree(tree, currentPath = [], paths = []) {
  if (!tree) return;
  
  for (const node of tree) {
    const nodePath = currentPath.concat(node.name);
    paths.push(nodePath.join("/"));
    recursiveTree(node.children, nodePath, paths);
  }
  
  return paths;
}

console.log(recursiveTree(treeData));

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