一个json数组

var nodes = [
    {"id":2,"title":"第一级1","parentid":0},
    {"id":3,"title":"第二级1","parentid":2},
    {"id":4,"title":"第二级2","parentid":2},
    {"id":5,"title":"第三级1","parentid":4},
    {"id":6,"title":"第三级2","parentid":3}
];

如何用递归的方式,转成如下树状格式:

var treeData = {
    "id": "2",
    "title": "第一级1",
    "children": [
        {
            "id": "3",
            "title": "第二级1",
            "children": [
                {
                    "id": "6",
                    "title": "第三级2",
                    "children": [
                        
                    ]
                }
            ]
        },
        {
            "id": "4",
            "title": "第二级2",
            "children": [
                {
                    "id": "5",
                    "title": "第三级1",
                    "children": [
                        
                    ]
                }
            ]
        }
    ]
}
/**
     * 数组转成树状结构
     * @param data 数据结构 [{
            "_parentId": 14,
            "gmtCreate": "2019-01-15 09:44:38",
            "gmtUpdate": "2019-01-15 09:44:38",
            "id": 15,
            "isShow": 1,
            "name": "用户注册",
            "orderIndex": 10000,
            "parentId": 14
        },...]
     * @param pid 初始父节点id,一般是0
     * @return [{
          label: '一级 1',
          children: [{
            label: '二级 1-1',
            children: [{
              label: '三级 1-1-1'
            }]
          }]
        }
     */
    convertToTreeData(data, pid) {
      const result = []
      let temp = []
      for (let i = 0; i < data.length; i++) {
        if (data[i].parentid === pid) {
          const obj = { 'title': data[i].name, 'id': data[i].id }
          temp = this.convertToTreeData(data, data[i].id)
          if (temp.length > 0) {
            obj.children = temp
          }
          result.push(obj)
        }
      }
      return result
    }

使用方式:

var nodes = [
    {"id":2,"title":"第一级1","parentid":0},
    {"id":3,"title":"第二级1","parentid":2},
    {"id":4,"title":"第二级2","parentid":2},
    {"id":5,"title":"第三级1","parentid":4},
    {"id":6,"title":"第三级2","parentid":3}
];
const treeData = convertToTreeData(nodes, 0)
console.log(treeData)
GitHub 加速计划 / js / json
41.72 K
6.61 K
下载
适用于现代 C++ 的 JSON。
最近提交(Master分支:1 个月前 )
960b763e 4 个月前
8c391e04 6 个月前
Logo

旨在为数千万中国开发者提供一个无缝且高效的云端环境,以支持学习、使用和贡献开源项目。

更多推荐