Skip to content
On this page

listToTree

基本使用

转换前:
[
  {
    "id": "1",
    "title": "节点1",
    "parentId": ""
  },
  {
    "id": "1-1",
    "title": "节点1-1",
    "parentId": "1"
  },
  {
    "id": "2",
    "title": "节点2",
    "parentId": ""
  },
  {
    "id": "2-1",
    "title": "节点2-1",
    "parentId": "2"
  },
  {
    "id": "2-2",
    "title": "节点2-2",
    "parentId": "2"
  }
]
转换后:
[
  {
    "id": "1",
    "title": "节点1",
    "parentId": "",
    "children": [
      {
        "id": "1-1",
        "title": "节点1-1",
        "parentId": "1",
        "children": []
      }
    ]
  },
  {
    "id": "2",
    "title": "节点2",
    "parentId": "",
    "children": [
      {
        "id": "2-1",
        "title": "节点2-1",
        "parentId": "2",
        "children": []
      },
      {
        "id": "2-2",
        "title": "节点2-2",
        "parentId": "2",
        "children": []
      }
    ]
  }
]
vue
<template #component>
转换前:
<kn-format-json :data = "list" />
转换后:
<kn-format-json :data = "tree" />
</template>
<script setup>
import { listToTree,KnFormatJson } from 'knot-vue'
const list = [
  {
    id: '1',
    title: '节点1',
    parentId: '',
  },
  {
    id: '1-1',
    title: '节点1-1',
    parentId: '1'
  },
  {
    id: '2',
    title: '节点2',
    parentId: ''
  },
  {
    id: '2-1',
    title: '节点2-1',
    parentId: '2'
  },
  {
    id: '2-2',
    title: '节点2-2',
    parentId: '2'
  },
]
const tree = listToTree(list)

</script>

API

属性名描述类型是否必填默认值
第一个参数扁平列表Item[] 见下表true--
第二个参数唯一标识字段名stringtrueid
第三个参数子节点数组字段名stringtruechildren
第四个参数父节点唯一标识字段名stringtrueparentId

Item

属性名描述类型是否必填默认值
id唯一标识stringtrue--
children子节点数组stringtrue--
parentId父节点唯一标识stringtrue--

Released under the MIT License.