jsでjsonArayを再帰する方法を樹形のjsonオブジェクトに変換します.

14448 ワード

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)