将对象数组转换为嵌套对象数组js

时间:2020-06-22 18:52:33

标签: javascript arrays sorting lodash

因此,我有一个任务来正确排序文件目录。为了简单起见,所有文档和文件都保存为平面数组。作为显示嵌套文件的标识符,我有一个属性 uniqueId ,它告诉我什么是父目录。平面数组按 uniqueId 排序,以便每个子项都跟随其父项。

以下是平面数组的示例:

[{
 id: 1,
 uniqueId: '1',
 name: 'folder1',
 dir: true
},
{
 id: 2,
 uniqueId: '1.2',
 name: 'test1',
 dir: false
},
{
 id: 3,
 uniqueId: '1.2.3',
 name: 'test2'
 dir: false
},
{
 id: 4,
 uniqueId: '1.2.4',
 name: 'test3'
 dir: true
},
{
 id: 3,
 uniqueId: '1.3',
 name: 'test23'
 dir: true
},
{
 id: 1,
 uniqueId: '1.3.1',
 name: 'test6',
 dir: true
},
]

基本上代表文件目录树:

1
  1.2
    1.2.3
    1.2.4
  1.3
    1.3.1

我需要首先显示目录,即具有dir: true的目录。因此,上面的树将变为:

1
 1.3
    1.3.1
 1.2
    1.2.4
    1.2.3

因此,作为解决方案,我决定将平面数组转换为嵌套对象,以所需的方式对每个对象的子级进行排序,然后再次转换回平面数组,这是更好的选择。这样我的平面数组将变成这样:

{
 id: 1,
 uniqueId: '1',
 name: 'folder1',
 dir: true
 childs: [
  {
   id: 2,
   uniqueId: '1.2',
   name: 'test1',
   dir: false,
   childs: [
   {
     id: 3,
     uniqueId: '1.2.3',
     name: 'test2'
     dir: false
   },
   {
     id: 4,
     uniqueId: '1.2.4',
     name: 'test3'
     dir: true
   }
 ]},
 {
   id: 3,
   uniqueId: '1.3',
   name: 'test23'
   dir: true,
   childs: [
    {
     id: 1,
     uniqueId: '1.3.1',
     name: 'test23'
     dir: true
    }
  ]
}
}]

我找不到将平面转换为所需嵌套对象的方法。我已经有一个返回当前对象 isChild(parent,objectToCheck)的子代的函数。我想最好为此使用某种递归,但我完全陷入困境。

请帮助我将其转换为所需的嵌套对象。

也欢迎任何其他对平面数组进行排序的建议!也许有一种更好的方法可以对它进行排序,而无需实际转换回来并强制执行?

非常感谢!

1 个答案:

答案 0 :(得分:1)

您可以直接对数据进行排序,并使用uniqueId和父值构建树。

const
    input = [{ id: 1, uniqueId: '1', name: 'folder1', dir: true }, { id: 2, uniqueId: '1.2', name: 'test1', dir: false }, { id: 3, uniqueId: '1.2.3', name: 'test2', dir: false }, { id: 4, uniqueId: '1.2.4', name: 'test3', dir: true }, { id: 3, uniqueId: '1.3', name: 'test23', dir: true }, { id: 1, uniqueId: '1.3.1', name: 'test6', dir: true }],
    tree = function (data) {
        var t = {};
        data.forEach(o => {
            const parent = o.uniqueId.split('.').slice(0, -1).join('.');
            Object.assign(t[o.uniqueId] = t[o.uniqueId] || {}, o);
            t[parent] = t[parent] || {};
            t[parent].children = t[parent].children || [];
            t[parent].children.push(t[o.uniqueId]);
        });
        return t[''].children;
    }(input.sort((a, b) => b.dir - a.dir));
   
console.log(tree);
.as-console-wrapper { max-height: 100% !important; top: 0; }