General situation of

JSON is widely used as an important presence for browser and service interaction. We use JS to implement a method to remove an empty field from JSON.

Consider what needs to be removed. Here are a few examples:

  • null
  • An empty array []
  • Empty string “” or” “

Train of thought

When I first saw it, I thought of the idea of deep copy, considering data types, loops, etc. Loop over an object, or if it is an array and an object, loop over RemoveEmptyFields, or delete it. Loop forEach uses a custom method to optimize speed.

implementation

// Define type 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]'// Need deep loop const deep = [arrayTag, objectTag] /** * optimization * usewhileTo implement a genericforEach iterates * @param {array} array * @param {func} iteratee */function forEach(array, iteratee) {
    let index = -1
    const length = array.length
    while (++index < length) {
        iteratee(array[index], index)
    }
    returnArray} // Get the typefunction getType(target) {
    returnObject. The prototype. ToString. Call (target)} / / deletedfunction 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}} // Delete Spacesfunction RemoveEmptyFields(obj) {
    const type = getType(obj)
    const keys = type=== arrayTag ? Undefined: object.keys (obj) // loopforEach(keys || obj, (value, key) => {
        if (keys) {
            key = value
        }
        if (canIRemove(obj[key], getType(obj[key]))) {
            delete obj[key]
        } else{// loop through arrays, objectsif (deep.includes(getType(obj[key]))) {
                RemoveEmptyFields(obj[key])
                if (isEmpty(obj[key])) {
                    delete obj[key]
                }
            }
        }
    })
    returnObj} // Whether it is nullfunction isEmpty(obj) {
    for (const key in obj) {
        if (obj.hasOwnProperty(key)) {
            return false}}return true
}

const json = {
    first_name: 'Sunnie',
    last_name: ' ',
    email: '[email protected]',
    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))Copy the code

The last

If you have any questions, leave comments and ask questions.

You can also scan the code to follow the public account



Add a group reply to join the “Front-end Fairy Group”