JS 中 JSON 数组转换树形结构
3年前
/**
*
* @param a json数组
* @param idStr id
* @param pidStr 父id
* @param childrenStr 子数组
* @returns {[]}
*/
export function transData(array, idStr, pidStr, childrenStr) {
let r = [], hash = {}, id = idStr, pid = pidStr, children = childrenStr, i = 0, j = 0, len = array.length;
for (; i < len; i++) {
hash[array[i][id]] = array[i];
}
for (; j < len; j++) {
let aVal = array[j], hashVP = hash[aVal[pid]];
if (hashVP) {
!hashVP[children] && (hashVP[children] = []);
hashVP[children].push(aVal);
} else {
r.push(aVal);
}
}
return r;
}