将数组转换为对象树[JS] [英] Transform array to object tree [JS]

查看:74
本文介绍了将数组转换为对象树[JS]的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

人们! 作为初级前端开发人员,这是我的第一个问题.

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

我具有函数( https://jsfiddle.net/kmjhsbt9/),该函数可以转换平面数组像这样:

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',
];

像这样进入对象树:

[
    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'
                           }
                      ]
                 ]
             }
        ]
    }
    .....
]

功能:

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

非常感谢您!

推荐答案

您可以通过递归地迭代输出对象的键(由getTree生成的键)来实现此目的:

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

这篇关于将数组转换为对象树[JS]的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆