从对象及其嵌套子对象中移除所有假值

Published on
Published on
/3 mins read/---

这个函数将从对象及其嵌套子对象中移除所有假值,如 nullundefined0''false

允许传入自定义的 falsyValues 来移除,并返回一个不包含假值的新对象。

remove-falsy.js
function removeFalsy(obj, falsyValues = ['', null, undefined]) {
  if (!obj || typeof obj !== 'object') {
    return obj
  }
  return Object.entries(obj).reduce((a, c) => {
    let [k, v] = c
    if (falsyValues.indexOf(v) === -1 && JSON.stringify(removeFalsy(v, falsyValues)) !== '{}') {
      a[k] = typeof v === 'object' && !Array.isArray(v) ? removeFalsy(v, falsyValues) : v
    }
    return a
  }, {})
}
使用示例
index.js
let obj = {
  a: 1,
  b: 0,
  c: '',
  d: null,
  e: undefined,
  f: false,
  g: {
    a: 1,
    b: 0,
    c: '',
    d: null,
    e: undefined,
    f: false,
  },
  j: {},
  h: [],
  i: [1],
}
 
console.log(removeFalsy(obj, [0, false, '', null, undefined]))
// 👉 { a: 1, g: { a: 1 }, i: [ 1 ] }

函数详解

参数说明

  • obj: 要处理的对象
  • falsyValues: 自定义的假值数组,默认为 ['', null, undefined]

工作原理

  1. 类型检查: 如果输入不是对象,直接返回原值
  2. 递归处理: 遍历对象的每个属性,递归处理嵌套对象
  3. 假值过滤: 移除在 falsyValues 数组中定义的值
  4. 空对象处理: 移除处理后变为空的对象 {}

更多使用场景

清理API响应数据

// 清理从API获取的数据
const apiResponse = {
  name: 'John',
  email: '',
  age: null,
  profile: {
    bio: undefined,
    avatar: 'image.jpg',
    settings: {},
  },
}
 
const cleanData = removeFalsy(apiResponse)
// 结果: { name: 'John', profile: { avatar: 'image.jpg' } }

表单数据处理

// 清理表单提交数据
const formData = {
  username: 'user123',
  password: 'secret',
  email: '',
  phone: null,
  preferences: {
    newsletter: false,
    notifications: true,
    theme: '',
  },
}
 
const cleanFormData = removeFalsy(formData, ['', null, undefined])
// 移除空字符串和null值,保留false

改进版本

支持数组深度清理的版本:

remove-falsy-advanced.js
function removeFalsyDeep(obj, falsyValues = ['', null, undefined]) {
  if (!obj) return obj
 
  if (Array.isArray(obj)) {
    return obj
      .map(item => removeFalsyDeep(item, falsyValues))
      .filter(item => falsyValues.indexOf(item) === -1)
  }
 
  if (typeof obj !== 'object') {
    return obj
  }
 
  return Object.entries(obj).reduce((acc, [key, value]) => {
    const cleanValue = removeFalsyDeep(value, falsyValues)
 
    if (falsyValues.indexOf(cleanValue) === -1) {
      // 如果是对象,检查是否为空对象
      if (typeof cleanValue === 'object' && !Array.isArray(cleanValue)) {
        if (Object.keys(cleanValue).length > 0) {
          acc[key] = cleanValue
        }
      } else {
        acc[key] = cleanValue
      }
    }
 
    return acc
  }, {})
}

注意事项

  • 函数会创建新对象,不会修改原对象
  • 空对象 {} 会被移除
  • 空数组 [] 默认会被保留
  • 可以通过 falsyValues 参数自定义要移除的值

Happy coding