JavaScript 常用 工具类

/**
 * 工具类
 * 2022年7月8日 22:52:24
 */



/**
 * 空校验 null或""都返回true
 */
export function isEmpty(obj) {
    if ((typeof obj === 'string')) {
        return !obj || obj.replace(/\s+/g, "") === ""
    } else {
        return (!obj || JSON.stringify(obj) === "{}" || obj.length === 0);
    }
}

/**
 * 非空校验
 */
export function isNotEmpty(obj) {
    return !isEmpty(obj);
}

/**
 * 对象复制
 */
export function copy() {
    if (isNotEmpty(obj)) {
        return JSON.parse(JSON.stringify(obj));
    }
}

/**
 * 使用递归将数组转为树形结构
 * 父ID属性为parent
 */
export function array2Tree(array, parentId) {
    if (isEmpty(array)) {
        return [];
    }

    const result = [];
    for (let i = 0; i < array.length; i++) {
        const c = array[i];

        // console.log(Number(c.parent), Number(parentId));

        if (Number(c.parent) === Number(parentId)) {
            result.push(c);

            // 递归查看当前节点对应的子节点
            const children = array2Tree(array, c.id);
            if (isNotEmpty(children)) {
                c.children = children;
            }
        }
    }
    return result;
}

posted @ 2022-10-13 19:30  咸瑜  阅读(47)  评论(0编辑  收藏  举报