Skip to content

toTree

js
toTree(data, parentValue, fieldNames)

线型数据结构转换成树型数据结构

参数

名称说明类型默认值
data数据列表array-
parentValue父级初始值number string0
fieldNames字段名object{ key: 'id', children: 'children', parentKey: 'parentId' }

示例

js
const data = [
    { id: '1', title: '选项1', parentId: '0' },
    { id: '1-1', title: '选项1-1', parentId: '1' },
    { id: '1-2', title: '选项1-2', parentId: '1' },
    { id: '2', title: '选项2', parentId: '0' },
    { id: '2-1', title: '选项2-1', parentId: '2' },
    { id: '2-2', title: '选项2-2', parentId: '2' },
]

const list = toTree(data)

console.log(list)
json
[
    {
        "id": "1",
        "title": "选项1",
        "parentId": "0",
        "children": [
            {
                "id": "1-1",
                "title": "选项1-1",
                "parentId": "1"
            },
            {
                "id": "1-2",
                "title": "选项1-2",
                "parentId": "1"
            }
        ]
    },
    {
        "id": "2",
        "title": "选项2",
        "parentId": "0",
        "children": [
            {
                "id": "2-1",
                "title": "选项2-1",
                "parentId": "2"
            },
            {
                "id": "2-2",
                "title": "选项2-2",
                "parentId": "2"
            }
        ]
    }
]

本文档内容版权为 XYAdmin 作者所有,保留所有权利。