删除json数据中的空字段(Remove Empty Fields from JSON)

3,099 阅读2分钟

概况

JSON 作为浏览器和服务交互重要的存在,被广泛的应用。我们用js来实现一个方法将json中的空字段删除。

考虑哪些需要被删除,下面举了几个例子:

  • null
  • 空数组 []
  • 空字符串 “”或者 “  ”

思路

刚看到的时候想到了深拷贝的思路,要考虑数据类型,循环等。 对对象进行循环,如果是数组和对象则循环调用 RemoveEmptyFields其他满足则删除。循环forEach 使用了自定义的方法,优化速度。

实现

// 定义类型
const arrayTag = '[object Array]'
const objectTag = '[object Object]'
const nullTag = '[object Null]'
const undefinedTag = '[object Undefined]'
const boolTag = '[object Boolean]'
const dateTag = '[object Date]'
const numberTag = '[object Number]'
const stringTag = '[object String]'
// 需要深度循环
const deep = [arrayTag, objectTag]
/**
 * 优化
 * 使用while来实现一个通用的forEach遍历
 * @param {array} array
 * @param {func} iteratee
 */
function forEach(array, iteratee) {
    let index = -1
    const length = array.length
    while (++index < length) {
        iteratee(array[index], index)
    }
    return array
}
//  获取类型
function getType(target) {
    return Object.prototype.toString.call(target)
}
// 删除
function canIRemove(target, type) {
    switch (type) {
        case nullTag:
        case undefinedTag:
            return true
        case stringTag:
            return target.trim().length < 1
        case objectTag:
            return Object.keys(target).length === 0
        case arrayTag:
            return target.length === 0
        case numberTag:
            return isNaN(target)
        default:
            return false
    }
}
// 删除空格
function RemoveEmptyFields(obj) {
    const type = getType(obj)
    const keys = type === arrayTag ? undefined : Object.keys(obj)
    // 循环
    forEach(keys || obj, (value, key) => {
        if (keys) {
            key = value
        }
        if (canIRemove(obj[key], getType(obj[key]))) {
            delete obj[key]
        } else {
            // 循环数组、对象
            if (deep.includes(getType(obj[key]))) {
                RemoveEmptyFields(obj[key])
                if (isEmpty(obj[key])) {
                    delete obj[key]
                }
            }
        }
    })
    return obj
}
// 是否为空
function isEmpty(obj) {
    for (const key in obj) {
        if (obj.hasOwnProperty(key)) {
            return false
        }
    }
    return true
}

const json = {
    first_name: 'Sunnie',
    last_name: '',
    email: 'sunniejs@163.com',
    phone: undefined,
    gender: null,
    age: NaN,
    emptyArr: [],
    emptyObj: { from: '', code: null },
    emptyArr1: [[{ from: '', code: null }], {}],
    invitations: [{ from: '', code: null }],
    company: { name: '', industries: ['E-commerce', 'finance'], quit: false },
    address: {
        city: 'ShangHai',
        street: ' ',
        zip: '',
        street: {
            value1: 'PuDong',
            value2: ' ',
            value3: '',
        },
    },
    date: new Date(),
    interest: ['english', 'running', 'cycling'],
    settle: true,
}

console.log(RemoveEmptyFields(json))

最后

大家如果有疑问留言讨论,提出问题。

    你也可以扫码关注公众号


回复加群,即可加入”前端仙女群“