uniapp 移出对象内的空参数 空字段 空对象

uniapp yekong 1144℃

uniapp开发微信小程序时,接口要求如果对象中的值是空的那么就移除对应的字段,不提交到接口。

js移出对象中的空字段

但是移除后会影响现有的对象,于是考虑使用深拷贝,避免干扰现有的字段。

移出空字段方法

function toType (obj) {
  return ({}).toString.call(obj).match(/\s([a-zA-Z]+)/)[1].toLowerCase()
}

function filterNull (o) {
  for (var key in o) {
    if (o[key] === null || o[key] === '' || o[key] === undefined) {
      delete o[key]
    }
    if (toType(o[key]) === 'string') {
      o[key] = o[key].trim()
    } else if (toType(o[key]) === 'object') {
      o[key] = filterNull(o[key])
    } else if (toType(o[key]) === 'array') {
      o[key] = filterNull(o[key])
    }
  }
  return o
}

使用

需要安装lodash

	import {
		filterNull
	} from '@/utils/util.js'
	import _ from 'lodash'
	
	var data = filterNull(_.cloneDeep(this.data))
				AddOrEditCarType(data, {
					custom: {
						auth: true
					}
				}).then(res => {
					uni.hideLoading()
					if (res.Code == 200) {
						if (this.data.Id) {
							this.$refs['showToast'].success('更新成功');
						} else {
							this.$refs['showToast'].success('添加成功');
						}
						setTimeout(() => {
							uni.navigateBack({})
						}, 2000)

					}
				}).catch(err => {

				})
喜欢 (0)