簡體   English   中英

將對象數組轉換為嵌套對象數組js

[英]Convert an array of objects into an array of nested objects js

所以我有一個任務來正確排序文件目錄。 為簡單起見,所有文檔和文件都保存為平面數組。 作為顯示嵌套文件的標識符,我有一個屬性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

因此,作為一種解決方案,我決定最好將平面數組轉換為嵌套的 object,以所需的方式對每個 object 的子項進行排序,然后再次轉換為平面數組。 這樣我的平面數組就會變成這樣:

{
 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
    }
  ]
}
}]

我找不到將平面轉換為所需嵌套 object 的方法。 我已經有一個 function 返回當前 object isChild(parent, objectToCheck)的孩子。 我想最好為此使用某種遞歸,但我完全被卡住了。

請幫助我將其轉換為所需的嵌套 object。

也歡迎任何有關對平面數組進行排序的其他方法的建議? 也許有更好的方法來排序它而無需實際轉換回來並強制?

提前非常感謝!

您可以直接對數據進行排序並使用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; }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM