js统一处理后端返回的null、undefined、空字符串

统一格式化后端返回的数据
该方法直接修改原数据 可以直接修改vue传递下来的props值

示例

// 格式化前
a:{
	a1: undefined,
	a2: {
		b1: null
	},
	a3: [{ c1: null  }],
	a4: ''
}

// 格式化后
a:{
	a1: '-',
	a2: {
		b1: '-'
	},
	a3: [{ c1: '-'  }],
	a4: '-'
}
/**
*@params obj 要格式化的数组或者对象  type 将undefined、null、'' 要转化的内容
*/
export const formartData = <T>(obj:T, type = '-'):T => {
    
    
  if (Object.prototype.toString.call(obj) === '[object Object]'  || Object.prototype.toString.call(obj) === '[object Array]') {
    
    
    formart(obj, type)
    return obj
  } else {
    
    
    return obj
  }
}


const formart = (val, type) => {
    
    
  if (Object.prototype.toString.call(val) === '[object Object]') {
    
    
    for (const key in val) {
    
    
      if (val[key] === null || val[key] === undefined || val[key] === '') {
    
    
        val[key] = type
      } else if (Object.prototype.toString.call(val[key]) === '[object Object]'  || Object.prototype.toString.call(val[key]) === '[object Array]') {
    
    
        formart(val[key], type)
      }
    }
  } else {
    
    
    val.forEach(item => {
    
    
      if (Object.prototype.toString.call(item) === '[object Object]'  || Object.prototype.toString.call(item) === '[object Array]') {
    
    
        formart(item, type)
      }
    })
  }
}

猜你喜欢

转载自blog.csdn.net/weixin_44441196/article/details/120966864