tx

wangcx

栖迟於一丘,则天下不易其乐
54,392
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;
}
2 条评论
user 编辑评论信息
插入图片

隐私评论
  1. @
    qzfazxfwmw 3月2日
    Windows 10 · 搜狗浏览器 · 北京市 诚亿时代网络

    网络流行语融入自然,贴近年轻读者。

  2. @
    lpvhskomjs 3月2日
    Windows 10 · 搜狗浏览器 · 北京市 诚亿时代网络

    建议多用口语化表达,拉近与读者距离。

随机一言

:D 获取中...

随机文章

MySQL 的 now() 函数 1301 浏览 - 2023/02/07
JWT Token 865 浏览 - 2021/01/26
JS 中 JSON 数组转换树形结构 862 浏览 - 2022/04/24
Homebrew 修改源 870 浏览 - 2020/05/14
macOS JDK 多版本配置及切换 955 浏览 - 2019/10/11