Skip to content

Instantly share code, notes, and snippets.

@jerrybendy
Created March 29, 2019 02:23
Show Gist options
  • Save jerrybendy/e62a9c06666096adfa98dd40de4aa403 to your computer and use it in GitHub Desktop.
Save jerrybendy/e62a9c06666096adfa98dd40de4aa403 to your computer and use it in GitHub Desktop.
Convert flat data to tree format 平铺格式转树状结构
/**
* 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