sodiray / radash

Functional utility library - modern, simple, typed, powerful
https://radash-docs.vercel.app
MIT License
4.1k stars 160 forks source link

Feature Request: Convert flat array objects to tree-like data #399

Open narukeu opened 3 months ago

narukeu commented 3 months ago

I would like to request a new feature that can convert flat array objects into tree-like data. I believe this is a common and interesting feature. I believe Radash can provide a better function for constructing tree-like data (compared to writing it ourselves), and it would be beneficial for other JavaScript developers to learn. Thank you.

For example, given the following original data,

const origin = [
  {
    id: "8ae93d4b-1e19-4638-b970-50f2a0bc9ae8",
    name: "a",
    parentId: "",
  },
  {
    id: "cbef454d-c92b-4119-82b6-1867c430b891",
    name: "aa",
    parentId: "8ae93d4b-1e19-4638-b970-50f2a0bc9ae8",
  },
  {
    id: "ae35ddc8-8606-483b-bf48-0eb5f54da3c7",
    name: "aaa",
    parentId: "cbef454d-c92b-4119-82b6-1867c430b891",
  },
  {
    id: "7f8dabc0-665f-42d3-9862-1938f12227ab",
    name: "b",
    parentId: "",
  },
  {
    id: "62bf89ae-6307-431f-b0de-e1242ba105d1",
    name: "ba",
    parentId: "7f8dabc0-665f-42d3-9862-1938f12227ab",
  },
];

I hope to get the following result:


const result = [
  {
    id: "8ae93d4b-1e19-4638-b970-50f2a0bc9ae8",
    name: "a",
    parentId: "",
    children: [
      {
        id: "cbef454d-c92b-4119-82b6-1867c430b891",
        name: "aa",
        parentId: "8ae93d4b-1e19-4638-b970-50f2a0bc9ae8",
        children: [
          {
            id: "ae35ddc8-8606-483b-bf48-0eb5f54da3c7",
            name: "aaa",
            parentId: "cbef454d-c92b-4119-82b6-1867c430b891",
          },
        ],
      },
    ],
  },
  {
    id: "7f8dabc0-665f-42d3-9862-1938f12227ab",
    name: "b",
    parentId: "",
    children: [
      {
        id: "62bf89ae-6307-431f-b0de-e1242ba105d1",
        name: "ba",
        parentId: "7f8dabc0-665f-42d3-9862-1938f12227ab",
      },
    ],
  },
];