/*
# **********************************************************
# * Author : 夜路沏茶
# * Technical :
# * Filename : utils/index.js
# * Version : 0.1
# * Description : 简化数据
# * -------------------------------------------------------
# * Last modified : 2021-8-20 16:14:36
# * Last Update Log : 初版
# * *******************************************************
*/
/**
* 简化请求
* @param vm 原有请求
* @param rule 简化规则
* @param deep 深度
* e.g. console.log(conciseRequest({ a: 'a', b: null, c: 'c', d: '', e: undefined, f: NaN, g: ' ', h: { a: 1, b: '', c: null }, i: [0, 1, 2], l: [] }, ['NaN', 'null']))
*/
export function conciseRequest(vm, rule, deep) {
if (!rule) { rule = ['', 'undefined', 'null', 'NaN'] }
if (!deep) { deep = false }
const result = function(vm, rules, deep) {
Object.keys(vm).forEach(item => {
if (rules.indexOf(getType(vm[item])) > -1) delete vm[item]
// TODO: 2021-8-20 对象深度简化
})
return vm
}
return result(vm, rule, deep)
}
/**
* 获取数据类型
* @param vm 数据对象
* @returns {string|"undefined"|"object"|"boolean"|"number"|"string"|"function"|"symbol"|"bigint"}
*/
export function getType(vm) {
// 为空、未定义、NULL 直接返回 不做类型判断
if (vm === '') return ''
if (vm === undefined) return 'undefined'
if (vm === null) return 'null'
// 判断数字
if (typeof vm === 'number' && isNaN(vm)) return 'NaN'
if (typeof vm === 'number') return 'Number'
// 判断字符串
if (vm.constructor.name === 'String') {
// 字符串为空串是,显示为空 (方便排除空值)
if (vm.trim() === '') return ''
return 'String'
}
// 判断数组
if (Array.prototype.isPrototypeOf(vm)) {
// 数组为空时,显示为空 (方便排除空值)
if (vm.length === 0) return ''
return 'Array'
}
// 判断函数
if (vm instanceof Function) return 'Function'
// 判断日期、错误对象等一系列对象
if (vm instanceof Object) return 'Object'
// 不存在则直接 typeof
return typeof vm
}
js获取类型 简化数据对象
最新推荐文章于 2022-05-25 14:19:28 发布