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

196
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar

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 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