0

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
1
  • children[] should be children : [] (typo, probably). Also your .map function isn't returning anything, it should. Or use forEach if you're not interested in what map returns. Commented Dec 27, 2021 at 15:28

2 Answers 2

2

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)

Sign up to request clarification or add additional context in comments.

Comments

1

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.