Home > database >  How to get path_name in recursive funciton javascript?
How to get path_name in recursive funciton javascript?

Time:12-28

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

CodePudding user response:

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)

CodePudding user response:

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

  • Related