05 - json转成树状结构
1 var jsonData = eval(`[ 2 {"id":"4","pid":"1","name":"大家电"}, 3 {"id":"5","pid":"1","name":"生活电器"}, 4 {"id":"1","pid":"0","name":"家用电器"}, 5 {"id":"2","pid":"0","name":"服饰"}, 6 {"id":"3","pid":"0","name":"化妆"}, 7 {"id":"7","pid":"4","name":"空调"}, 8 {"id":"8","pid":"4","name":"冰箱"}, 9 {"id":"9","pid":"4","name":"洗衣机"}, 10 {"id":"10","pid":"4","name":"热水器"}, 11 {"id":"11","pid":"3","name":"面部护理"}, 12 {"id":"12","pid":"3","name":"口腔护理"}, 13 {"id":"13","pid":"2","name":"男装"}, 14 {"id":"14","pid":"2","name":"女装"}, 15 {"id":"15","pid":"7","name":"海尔空调"}, 16 {"id":"16","pid":"7","name":"美的空调"}, 17 {"id":"19","pid":"5","name":"加湿器"}, 18 {"id":"20","pid":"5","name":"电熨斗"} 19 ]`); 20 21 function transData(data, idStr, pidStr, chindrenStr) { 22 var arr = [], 23 hash = {}, 24 id = idStr, 25 pid = pidStr, 26 children = chindrenStr; 27 28 for (var i = 0; i < data.length; i++) { 29 hash[data[i][id]] = data[i]; 30 } 31 for (var j = 0; j < data.length; j++) { 32 //data 中每一项 33 var arrVal = data[j], 34 //找父分类 35 hashVP = hash[arrVal[pid]]; 36 //pid 不为 0 37 if (hashVP) { 38 !hashVP[children] && (hashVP[children] = []); 39 hashVP[children].push(arrVal); 40 } 41 //pid 为 0 42 else { 43 // 将data 的对象添加到数组中 44 arr.push(arrVal); 45 } 46 } 47 return arr; 48 } 49 50 var jsonDataTree = transData(jsonData, 'id', 'pid', 'chindren'); 51 console.log(jsonDataTree);