首页 > 编程语言 >JavaScript 常用 工具类

JavaScript 常用 工具类

时间:2022-10-13 19:45:51浏览次数:45  
标签:function 常用 return JavaScript children export obj array 工具

/**
 * 工具类
 * 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;
}

标签:function,常用,return,JavaScript,children,export,obj,array,工具
From: https://www.cnblogs.com/bi-hu/p/16789408.html

相关文章