41、常用方法集合

102 阅读2分钟

1、过滤表单中key不存在的字段

 /**
     * @description: 过滤表单中key不存在的字段
     * @param {object} values 表单值 filterValue
     * @param {boolean} filterValue 是否过滤表单中value为 undefined | null 的字段
     * @return: 返回过滤后的表单值
     */
    formFilter(values, filterValue = true) {
        if(Object.prototype.toString.call(values) !== '[object Object]') {
            return {}
        }
        Object.keys(values).map(item => {
            if(!item) {
                delete values[item]
                return
            }
            if(filterValue && (values[item] === undefined || values[item] === null) ) {
                delete values[item]
            }
        })
        return values
    },

2、表单回显填充数据

/**
     * @description: 表单回显填充数据
     * @param {object} formData 表单原始对象
     * @param {object} newData 要填充的数据对象
     */
    formSetData(formData, newData) {
        Object.keys(formData).map(item => {
            if(newData[item] != undefined) {
                formData[item] = newData[item]
            }
        })
    },

3、判定数据类型

  /**
     * @method getDataType() 判定数据类型
     * @param {any} object 传入的数据类型
     * @returns {string} 数据类型,均为小写
     */
    getDataType(object) {
        // IE9下调用toString.call(undefined)报错
        if (typeof object === 'undefined') {
            return 'undefined'
        }
        let map = {
            '[object Number]': 'number',
            '[object String]': 'string',
            '[object Boolean]': 'boolean',
            '[object Object]': 'object',
            '[object Array]': 'array',
            '[object RegExp]': 'regExp',
            '[object Function]': 'function',
            '[object Promise]': 'promise',
            '[object GeneratorFunction]': 'generatorFunction',
            '[object Null]': 'null',
        }
        let typeString = ''
        if (object instanceof Element) {
            typeString = 'element'
        } else {
            typeString = map[Object.prototype.toString.call(object)]
        }
        return typeString
    },

4、深拷贝

//深拷贝
    deepCopy(obj) {
        // Hash表 记录所有的对象引用关系
        let map = new WeakMap();
        function dp(obj) {
            let result = null;
            let keys = null,
                key = null,
                temp = null,
                existObj = null;

            existObj = map.get(obj);
            // 如果这个对象已被记录则直接返回
            if (existObj) {
                return existObj;
            }
            keys = Object.keys(obj);
            result = {};
            // 记录当前对象
            map.set(obj,result);
            for (let i = 0; i < keys.length; i++) {
                key = keys[i];
                temp = obj[key];
                // 如果字段的值也是一个对象则递归复制
                if (temp && (Object.prototype.toString.call(temp) === '[object Array]' || Object.prototype.toString.call(temp) === '[object Object]')) {
                    result[key] = dp(temp);
                } else {
                    // 否则直接赋值给新对象
                    result[key] = temp;
                }
            }
            return result;
        }
        return dp(obj);
    },
    
    /**
     * 深度克隆对象,不支持对象内方法的克隆
     * @param {Objectany} source 待拷贝对象
     * @returns {Object}
     */
    deepClone(source) {
        return JSON.parse(JSON.stringify(source))
    },

5、格式化时间

/**
     * @method TimeFormat()格式化时间
     * @param {Date} time 需要格式化的时间 Date对象
     * @param {String} format 需要格式化成的格式
     */
    timeFormat: (time, format) => {
        let [year, month, day, hour, minutes, seconds] = [
            time.getFullYear(),
            (time.getMonth() + 1) >= 10 ? (time.getMonth() + 1) : '0' + (time.getMonth() + 1),
            time.getDate() >= 10 ? time.getDate() : '0' + time.getDate(),
            time.getHours() >= 10 ? time.getHours() : '0' + time.getHours(),
            time.getMinutes() >= 10 ? time.getMinutes() : '0' + time.getMinutes(),
            time.getSeconds() >= 10 ? time.getSeconds() : '0' + time.getSeconds()
        ]
        switch (format) {
        case 'Y-M-D':
            return `${year}-${month}-${day}`
        case 'Y.M.D':
            return `${year}.${month}.${day}`
        case '年-月-日 H:M:S':
            return `${parseInt(year, 10)}${temp.$t('Year')}${parseInt(month, 10)}${temp.$t('Month')}${parseInt(day, 10)}${temp.$t('day')} ${hour}:${minutes}:${seconds}`
        case `年-月-日`:
            return `${parseInt(year, 10)}${temp.$t('Year')}${parseInt(month, 10)}${temp.$t('Month')}${parseInt(day, 10)}${temp.$t('day')}`
        case 'H:M:S':
            return hour + ':' + minutes + ':' + seconds
        default:
            return `${year}-${month}-${day} ${hour}:${minutes}:${seconds}`
        }
    },