tx

wangcx

栖迟於一丘,则天下不易其乐
21,038
JS 中 JSON 数组转换树形结构 JS 中 JSON 数组转换树形结构
/**
 *
 * @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;
}
0 条评论
user 编辑评论信息
插入图片

隐私评论