Transform array to object tree [JS]

蹲街弑〆低调 提交于 2021-02-08 10:13:22

问题


People! It's my first question here as junior frontend dev.

I have function (https://jsfiddle.net/kmjhsbt9/) which transforms a flat array like this :

const filePaths = [
  'src/lib/git.js',
  'src/lib/server.js',
  'build/css/app.css',
  'externs/test/jquery.js',
];

into object tree like this:

[
    src: {
            lib: {
                git.js: 'file',
                server.js: 'file',
            }
    },
    build: {
        css: {
            app.css: 'file'
        }
    }
    .....
]

Please, help me to understand how I can rewrite the function so that it outputs the result in this format:

 [
    {
         text: src,
         children: [
              {
                   text: 'lib',
                   children: [
                         {
                             text: git.js,
                             children: [
                                  {
                                      text: 'file'
                                  },
                             ]
                         }, 
                         {
                             text: server.js,
                             children: [
                                  {
                                      text: 'file'
                                  },
                             ]
                         }

                   ]
              }
         ]

    },
    {
        text: build,
        children: [
             {
                 text: app.css,
                 children: [
                      text: app.css,
                      children: [
                           {
                                text: 'file'
                           }
                      ]
                 ]
             }
        ]
    }
    .....
]

function:

const getTree = (arr) => {
  let fileTree = [];

  function mergePathsIntoFileTree(prevDir, currDir, i, filePath) {
    if (!prevDir.hasOwnProperty(currDir)) {
      prevDir[currDir] = {};
    }

    if (i === filePath.length - 1) {
      prevDir[currDir] = 'file';
    }

    return prevDir[currDir];
  }

  function parseFilePath(filePath) {
    let fileLocation = filePath.split('/');

    if (fileLocation.length === 1) {
      return (fileTree[fileLocation[0]] = 'file');
    }

    fileLocation.reduce(mergePathsIntoFileTree, fileTree);
  }

  arr.forEach(parseFilePath);

  return fileTree;
}

Thank you very much, in advance!


回答1:


You can achieve this by recursively iterating over the keys of the output object (the one that gets generated by getTree):

const filePaths = [
  'src/lib/git.js',
  'src/lib/server.js',
  'build/css/app.css',
  'externs/test/jquery.js',
];

// building the dependecy tree,
//an alternative version to your "getTree" function, but a bit cleaner
function getTree(filePaths) {

    return filePaths.reduce((all, item) => {

        let pointer = null;

        item.split('/').forEach((el, i, arr) => {

            if (!i) pointer = all;

            if (!pointer.hasOwnProperty(el)) {
                pointer[el] = (i === arr.length - 1) ? 'file' : {};
            }

            pointer = pointer[el];

        });

        return all;

    }, {});

}

// formatting the dependency tree to match the desired output with recursion
function buildChildTree(obj) {

    return Object.keys(obj).map(key => {

        return {
            text: key,
            children: obj[key] === 'file' ? [{text:'file'}] : buildChildTree(obj[key])
        }

    });

}

const dependencyTree = getTree(filePaths);
const result = buildChildTree(dependencyTree);

console.log(JSON.stringify(result, null, 2));


来源:https://stackoverflow.com/questions/51938717/transform-array-to-object-tree-js

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!