首页 > 代码库 > js List<Map> 将偏平化的数组转为树状结构并排序

js List<Map> 将偏平化的数组转为树状结构并排序

 数据格式:

[{"id":"d3e8a9d6-e4c6-4dd8-a94f-07733d3c1b59","parentId":"6d460008-38f7-479d-b6d1-058ebc17dae3",
"myorder":1,"name":"任务一"},{"id":"6d460008-38f7-479d-b6d1-058ebc17dae3","parentId":"33978737-c722-4339-88a1-a9829dd4bca2",
"myorder":1,"name":"项目一"},{"id":"33978737-c722-4339-88a1-a9829dd4bca2","parentId":"5461ed61-543c-4ea1-9cb5-17b008e093a0",
"myorder":1,"name":"课题一"},{"id":"5461ed61-543c-4ea1-9cb5-17b008e093a0","parentId":"57e06272-eab4-4920-ae6a-25e055374851",
"myorder":1,"name":"电子教案"},{"id":"8d0723db-9087-4c83-8d0e-ab7f24ddf066","parentId":"6d460008-38f7-479d-b6d1-058ebc17dae3","name":"任务二",
"myorder":2}]

 

 1 var _data =http://www.mamicode.com/ ${videoList} 2     // 将偏平化的数组转为树状结构 -- id为根节点 3     function filterArray(data, id) { 4         var fa = function(parentid) { 5             var _array = []; 6             for (var i = 0; i < data.length; i++) { 7                 var n = data[i]; 8                 if (n.parentId === parentid) { 9                     n.children = fa(n.id);10                     _array.push(n);11                 }12             }13             return _array;14         }15         return fa(id);16     }17   //根据myorder排序18     function _sort(data){19         for(var i =0; i<data.length; i++){20             _sort(data[i].children)21         }22         data.sort(function(a,b){23             return a.myorder>b.myorder24         })25     }
var data =http://www.mamicode.com/ filterArray(_data, id)            _sort(data)

 

js List<Map> 将偏平化的数组转为树状结构并排序