/** * json格式轉樹狀結構 * @param {json} json數據 * @param {String} id的字符串 * @param {String} 父id的字符串 * @param {String} children的字符串 * @return {Array} 數組 */ function transData(a, idStr, pidStr, chindrenStr){ var r = [], hash = {}, id = idStr, pid = pidStr, children = chindrenStr, i = 0, j = 0, len = a.length; for(; i < len; i++){ hash[a[i][id]] = a[i]; } for(; j < len; j++){ var aVal = a[j], hashVP = hash[aVal[pid]]; if(hashVP){ !hashVP[children] && (hashVP[children] = []); hashVP[children].push(aVal); }else{ r.push(aVal); } } return r; } var jsonData = eval('[ {"id":"4","pid":"1","name":"你們電"}, {"id":"5","pid":"1","name":"生活電器"}, {"id":"1","pid":"0","name":"家用電器"}, {"id":"2","pid":"0","name":"服飾"}, {"id":"3","pid":"0","name":"化妝"}, {"id":"7","pid":"4","name":"空調"}, {"id":"8","pid":"4","name":"冰箱"}, {"id":"9","pid":"4","name":"洗衣機"}, {"id":"10","pid":"4","name":"熱水器"}, {"id":"11","pid":"3","name":"面部護理"}, {"id":"12","pid":"3","name":"口腔護理"}, {"id":"13","pid":"2","name":"男裝"}, {"id":"14","pid":"2","name":"女裝"}, {"id":"15","pid":"7","name":"海爾空調"}, {"id":"16","pid":"7","name":"美的空調"}, {"id":"19","pid":"5","name":"加溼器"}, {"id":"20","pid":"5","name":"電熨斗"} ]'); var jsonDataTree = transData(jsonData, 'id', 'pid', 'chindren'); console.log(jsonDataTree); //結果以下: [ {"id":"1","pid":"0","name":"家用電器", "chindren":[ {"id":"4","pid":"1","name":"你們電", "chindren":[ {"id":"7","pid":"4","name":"空調", "chindren":[ {"id":"15","pid":"7","name":"海爾空調"}, {"id":"16","pid":"7","name":"美的空調"} ]}, {"id":"8","pid":"4","name":"冰箱"}, {"id":"9","pid":"4","name":"洗衣機"}, {"id":"10","pid":"4","name":"熱水器"} ]}, {"id":"5","pid":"1","name":"生活電器","chindren":[ {"id":"19","pid":"5","name":"加溼器"}, {"id":"20","pid":"5","name":"電熨斗"} ]} ]}, {"id":"2","pid":"0","name":"服飾","chindren":[ {"id":"13","pid":"2","name":"男裝"}, {"id":"14","pid":"2","name":"女裝"} ]}, {"id":"3","pid":"0","name":"化妝","chindren":[ {"id":"11","pid":"3","name":"面部護理"}, {"id":"12","pid":"3","name":"口腔護理"} ]} ]