Skip to content

cleanObjectEmptyValues

过滤对象中值为 undefined 和 null 的属性

引入版本

0.15.0

Demo

ts
import { cleanObjectEmptyValues } from '@wyfex/iutils'

/**
 * ================== 1. 单层对象 ==================
 */
const case1 = {
  id: 1,
  name: null,
  phone: undefined,
  age: 0,
  emptyStr: '',
  flag: false
}
console.log(cleanObjectEmptyValues(case1))
// {id: 1, age: 0, emptyStr: '', flag: false}

/**
 * ================== 2. 嵌套对象递归清洗 ==================
 */
const case2 = {
  user: {
    username: 'test',
    avatar: null,
    address: {
      city: undefined,
      code: '001'
    }
  },
  token: undefined
}
console.log(JSON.stringify(cleanObjectEmptyValues(case2), null, 2))
// {
//   "user": {
//     "username": "test",
//     "address": {
//       "code": "001"
//     }
//   }
// }

/**
 * ================== 3. 数组嵌套清洗 ==================
 */
const case3 = {
  list: [1, null, 'test', undefined, { a: null, b: 2 }]
}
console.log(JSON.stringify(cleanObjectEmptyValues(case3), null, 2))
// {
//   "list": [
//     1,
//     "test",
//     {
//       "b": 2
//     }
//   ]
// }

/**
 * ================== 4. 多层嵌套数组+对象混合 ==================
 */
const case4 = {
  data: [{ id: 1, info: null }, undefined, [99, undefined, null]]
}
console.log(JSON.stringify(cleanObjectEmptyValues(case4), null, 2))
// {
//   "data": [
//     {
//       "id": 1
//     },
//     [
//       99
//     ]
//   ]
// }

/**
 * ================== 5. 全空值对象 ==================
 */
console.log(cleanObjectEmptyValues({ a: null, b: undefined })) // {}

/**
 * ================== 6. 空对象 ==================
 */
console.log(cleanObjectEmptyValues({})) // {}

/**
 * ================== 7. 非法入参统一返回空对象 ==================
 */
console.log(cleanObjectEmptyValues(null))
console.log(cleanObjectEmptyValues(undefined))
console.log(cleanObjectEmptyValues(123))
console.log(cleanObjectEmptyValues([]))
console.log(cleanObjectEmptyValues('abc'))
// 全部输出 {}

/**
 * ================== 8. 边界值保留(0、false、''、NaN、Infinity) ==================
 */
const case8 = {
  zero: 0,
  empty: '',
  falseVal: false,
  nan: NaN,
  inf: Infinity
}
console.log(cleanObjectEmptyValues(case8))
// 全部字段保留

基于 MIT 许可发布