js 过滤对象以及数组对象中的null

js yekong 1209℃

微信小程序开发时,接口返回的数据有些没有值字段会带上null,但是客户要求不要显示null,所有页面没有值的话就显示空,但是页面实在太多了,有几十个页面,一个一个的改得改到啥时候呢?于是就想到了接口封装,在接口请求到数据后,先处理一下过滤掉null,再返回。
使用lodash方法判断是对象还是数组。

过滤方法

var newData = response.data.Data
// 如果是对象
if (_.isObject(newData)) {
	for (let k in newData) {
		newData[k] = newData[k] === null ? '' : newData[k]
	}
}
// 如果是数组
if (_.isArray(newData)) {
	newData.forEach((type) => {
		for (let k in type) {
			type[k] = type[k] === null ? '' : type[k]
		}
	});
}
response.data.Data = newData

封装实例

// 此vm参数为页面的实例,可以通过它引用vuex中的变量
import configs from './config.js'
import Qs from 'qs'

module.exports = (vm) => {
	// 初始化请求配置
	uni.$u.http.setConfig((config) => {
		/* config 为默认全局配置*/
		config.baseURL = configs.baseUrl; /* 根域名 */
		return config
	})

	// 请求拦截
	uni.$u.http.interceptors.request.use((config) => { // 可使用async await 做异步操作
		config.header['Content-Type'] = 'application/json'
		config.data = config.data || {}
		// uni.showLoading({
		// 	title: '加载中'
		// })
		if (config?.custom?.auth) {
			// 获取token
			// console.log('获取token2')
			// console.log(uni.getStorageSync('token'))
			if (uni.getStorageSync('token')) {
				config.header['Authorization'] = 'Bearer ' + uni.getStorageSync('token')
				// 可以在此通过vm引用vuex中的变量,具体值在vm.$store.state中
			} else {
				console.log('需要登录')
				uni.redirectTo({
					url: '/pages/login/login'
				})
			}
		}
		return config
	}, config => { // 可使用async await 做异步操作
		return Promise.reject(config)
	})

	// 响应拦截
	uni.$u.http.interceptors.response.use((response) => {
		uni.hideLoading({
			noConflict: true
		})
		/* 对响应成功做点什么 可使用async await 做异步操作*/
		var newData = response.data.Data
		if (_.isObject(newData)) {
			for (let k in newData) {
				newData[k] = newData[k] === null ? '' : newData[k]
			}
		}
		if (_.isArray(newData)) {
			newData.forEach((type) => {
				for (let k in type) {
					type[k] = type[k] === null ? '' : type[k]
				}
			});
		}
		response.data.Data = newData
		const data = response.data
		// 自定义参数
		// const custom = response.config?.custom
		if (data.Code != 200) {
			// 如果没有显式定义custom的toast参数为false的话,默认对报错进行toast弹出提示
			if (data.Message) {
				// uni.$u.toast(data.message)
				if (_.startsWith(data.Message, '将截断字符串或二进制数据')) {
					uni.showToast({
						title: '字符长度超过数据限制',
						icon: 'none'
					});
				} else {
					uni.showToast({
						title: data.Message,
						icon: 'none'
					});
				}
			}
			return data === undefined ? {} : data
		}
		return data === undefined ? {} : data
	}, (response) => {
		// 对响应错误做点什么 (statusCode !== 200)
		if (response.statusCode == 401) {
			uni.clearStorageSync()
			uni.$u.route('/pages/login/login')
		}
		if (response.statusCode == 400) {
			if (process.env.NODE_ENV === 'development') {
				console.log('开发环境')
				// console.log(response)
				// console.log(response.data)
				// console.log(response.data.errors)
				try {
					for (let i in response.data.errors) {
						if (response.data.errors[i][0]) {
							uni.showToast({
								title: response.data.errors[i][0],
								icon: 'none'
							});
							throw new Error("中断循环");
						}
					}
				} catch (e) {
					console.log(e)
				};
			} else {
				console.log('生产环境')
				uni.showToast({
					title: '异常错误',
					icon: 'none'
				});
			}
		}
		return Promise.reject(response)
	})
}

喜欢 (0)