Created
March 29, 2019 02:23
-
-
Save jerrybendy/e62a9c06666096adfa98dd40de4aa403 to your computer and use it in GitHub Desktop.
Convert flat data to tree format 平铺格式转树状结构
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* Convert flat data to tree format | |
* | |
* @see http://blog.csdn.net/chelen_jak/article/details/21290769 | |
* | |
* @param {array} a json数据 | |
* @param {String} idStr id的字符串 | |
* @param {String} pidStr 父id的字符串 | |
* @param {String} childrenStr children的字符串 | |
* @return {array} 数组 | |
*/ | |
function transData(a, idStr, pidStr, childrenStr){ | |
var r = [], hash = {}, children = childrenStr, i = 0, j = 0, len = a.length; | |
for(; i < len; i++){ | |
hash[a[i][idStr]] = a[i]; | |
} | |
for(; j < len; j++){ | |
var aVal = a[j], hashVP = hash[aVal[pidStr]]; | |
if(hashVP){ | |
!hashVP[children] && (hashVP[children] = []); | |
hashVP[children].push(aVal); | |
}else{ | |
r.push(aVal); | |
} | |
} | |
return r; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment