Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

198
Views
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 answers
Answer question

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 Report

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!