# listToTree

### 说明

&#x20;简将列表数据转化为树结构

### 源码

<https://github.com/ddzy/ts-utility-plugins/blob/master/src/ddzy/utility/others/listToTree/index.ts>

### 用法

{% code title="listToTree.test.ts" %}

```typescript
import listToTree from "../../utility/others/listToTree";

describe('listToTree tests()...', () => {
  test('listToTree should transform a list to a tree', () => {
    const received = [
      {
        id: 2,
        value: 2,
        parent: 1,
      },
      {
        id: 3,
        value: 3,
        parent: 0,
      },
      {
        id: 4,
        value: 4,
        parent: 3,
      },
      {
        id: 5,
        value: 5,
        parent: 3,
      },
      {
        id: 1,
        value: 1,
        parent: 0,
      },
      {
        id: 6,
        value: 6,
        parent: 4,
      },
      {
        id: 7,
        value: 7,
        parent: 4,
      },
      {
        id: 8,
        value: 8,
        parent: 7,
      },
    ];
    const expected = [
      {
        "id": 3,
        "value": 3,
        "parent": 0,
        "children": [
          {
            "id": 4,
            "value": 4,
            "parent": 3,
            "children": [
              {
                "id": 6,
                "value": 6,
                "parent": 4
              },
              {
                "id": 7,
                "value": 7,
                "parent": 4,
                "children": [
                  {
                    "id": 8,
                    "value": 8,
                    "parent": 7
                  }
                ]
              }
            ]
          },
          {
            "id": 5,
            "value": 5,
            "parent": 3
          }
        ]
      },
      {
        "id": 1,
        "value": 1,
        "parent": 0,
        "children": [
          {
            "id": 2,
            "value": 2,
            "parent": 1
          }
        ]
      }
    ];

    const result = listToTree(received);

    expect(result).toStrictEqual(expected);
  });
});
```

{% endcode %}


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://ddzy.gitbook.io/ts-utility-plugins-docs/utility/utility-others/listtotree.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
