Home > Enterprise >  Convert array of paths into a Tree in JavaScript
Convert array of paths into a Tree in JavaScript

Time:08-28

Given this input:

const paths = ["src", "src/components", "src/components/index.ts", "src/utils", "src/configuration/config.ts", "another/file.ts"];

I need to create a function or a data structure that returns a Tree with the following structure.

[
      {
            "id": "src",
            "level": 1,
            "childrens": [
                  {
                        "id": "src/components",
                        "level": 2,
                        "childrens": [
                              {
                                    "id": "src/components/index.ts",
                                    "level": 3,
                                    "childrens": []
                              }
                        ]
                  },
                  {
                        "id": "src/utils",
                        "level": 2,
                        "childrens": []
                  },
                  {
                        "id": "src/configuration",
                        "level": 2,
                        "childrens": [
                              {
                                    "id": "src/configuration/config.ts",
                                    "level": 3,
                                    "childrens": []
                              }
                        ]
                  }
            ]
      },
      {
            "id": "another",
            "level": 1,
            "childrens": [
                  {
                        "id": "another/file.ts",
                        "level": 2,
                        "childrens": []
                  }
            ]
      }
]

I tried everything but I can't make it work, so if anyone can help I would appreciate it a lot.

Thank you.

CodePudding user response:

Well yes basically split and recursion. lets try it. But first, here's the solution based on this answer: https://stackoverflow.com/a/57344801/3807365

const paths = ["src", "src/components", "src/components/index.ts", "src/utils", "src/configuration/config.ts", "another/file.ts"];

let result = [];
let level = {
  result
};

paths.forEach(path => {
  path.split('/').reduce((r, id, i, a) => {
    if (!r[id]) {
      r[id] = {
        result: []
      };
      r.result.push({
        id: a.slice(0, i   1).join("/"),
        level: i   1,
        children: r[id].result
      })
    }

    return r[id];
  }, level)
})

console.log(result)

Well I can't beat that. So that's my solution then.

CodePudding user response:

const paths = ["src", "src/components", "src/components/index.ts", "src/utils", "src/configuration/config.ts", "another/file.ts"];

result = {};
    
paths.forEach(p => p.split('/').reduce((o, k) => o[k] = o[k] || {}, result));

console.log(result);

  • Related