簡體   English   中英

根據對象的 id 創建一個新的對象數組

[英]Create a new array of object based on the ids of the objects

我需要根據列表中的 parent_id 將對象數組轉換為新數組。 在下面給定的輸入中,我們有一個 parent_id,它告訴使用給定對象的父級。

輸入

[
  {
    "id": 1,
    "title": "Item 1",
    "parent_id": null
  },
  {
    "id": 2,
    "title": "Item 2",
    "parent_id": 1
  },
  {
    "id": 3,
    "title": "Item 3",
    "parent_id": 2
  },
  {
    "id": 4,
    "title": "Item 4",
    "parent_id": null
  },
  {
    "id": 5,
    "title": "Item 5",
    "parent_id": null
  },
  {
    "id": 6,
    "title": "Item 6",
    "parent_id": 5
  },
  {
    "id": 7,
    "title": "Item 7",
    "parent_id": 6
  },
  {
    "id": 8,
    "title": "Item 8",
    "parent_id": 6
  }
]

期望輸出

[
  {
    "id": 1,
    "title": "Item 1",
    "parent_id": null,
    "child": [{
        "id": 2,
        "title": "Item 2",
        "parent_id": 1,
        "child": [{
            "id": 3,
            "title": "Item 3",
            "parent_id": 2
        }]
    }]
  },
  {
    "id": 4,
    "title": "Item 4",
    "parent_id": null
  },
  {
    "id": 5,
    "title": "Item 5",
    "parent_id": null,
    "child": [{
        "id": 6,
        "title": "Item 6",
        "parent_id": 5,
        "child": [{
            "id": 7,
            "title": "Item 7",
            "parent_id": 6
        }, {
            "id": 8,
            "title": "Item 8",
            "parent_id": 6
        }]
    }]
  }
]

在所需的輸出中,我創建了一個嵌套的對象數組,其中每個對象都將保存其子對象。 有人可以建議我們如何在javascript中做到這一點嗎?

只需在一個對象的幫助下進行一個循環並構建一棵樹。

 var data = [{ id: 1, title: "Item 1", parent_id: null }, { id: 2, title: "Item 2", parent_id: 1 }, { id: 3, title: "Item 3", parent_id: 2 }, { id: 4, title: "Item 4", parent_id: null }, { id: 5, title: "Item 5", parent_id: null }, { id: 6, title: "Item 6", parent_id: 5 }, { id: 7, title: "Item 7", parent_id: 6 }, { id: 8, title: "Item 8", parent_id: 6 }], tree = function (data, root) { var t = {}; data.forEach(o => { Object.assign(t[o.id] = t[o.id] || {}, o); t[o.parent_id] = t[o.parent_id] || {}; t[o.parent_id].children = t[o.parent_id].children || []; t[o.parent_id].children.push(t[o.id]); }); return t[root].children; }(data, null); 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