js移出对象中的空字段

js yekong 48℃

方法


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
}

使用

getdata () {
      var that = this
      var data = filterNull(this.searchdata)
      residualValue({
        ...data,
        pageSize: this.pageSize,
        pageNum: this.pageNum
      }).then(function (res) {
        that.tableData = res
      })
    }
喜欢 (4)