Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to deeply remove null values, empty objects and empty array from an object

Tags:

javascript

I have an object that looks like this:

var myObject = { a: { b: [{}], c: [{}, {d: 2}], e: 2, f: {} }, g:{}, h:[], i: [null, 2] }

I want to remove null values and and empty objects (array and objects) so that it looks like:

{ a: {c: [ {d: 2} ], e: 2 }, i: [ 2 ] }

The function should remove null values, empty objects and empty arrays. Any elegant way to do it ?

like image 544
JLavoie Avatar asked Jul 16 '26 11:07

JLavoie


1 Answers

Here is a function that clean the object recursively. It will loop deeply through all the properties and remove null values, null arrays and null objects:

cleanUpObject(jsonObject: object): object {

    Object.keys(jsonObject).forEach(function (key, index) {
        const currentObj = jsonObject[key]

        if (_.isNull(currentObj)) {
            delete jsonObject[key]
        } else if (_.isObject(currentObj)) {
            if (_.isArray(currentObj)) {
                if (!currentObj.length) {
                    delete jsonObject[key]
                } else {
                    const cleanupArrayObj = []
                    for (const obj of currentObj) {
                        if (!_.isNull(obj)) {
                            const cleanObj = this.cleanUpJson(obj)
                            if (!_.isEmpty(cleanObj)) {
                                cleanupArrayObj.push(cleanObj)
                            }
                        }
                    }
                    if (!cleanupArrayObj.length) {
                        delete jsonObject[key]
                    } else {
                        jsonObject[key] = cleanupArrayObj
                    }
                }
            } else {
                if (_.isEmpty(Object.keys(jsonObject[key]))) {
                    delete jsonObject[key]
                } else {
                    jsonObject[key] = this.cleanUpJson(currentObj)

                    if (_.isEmpty(Object.keys(jsonObject[key]))) {
                        delete jsonObject[key]
                    }
                }
            }
        }
    }, this)

    return jsonObject
}
like image 70
JLavoie Avatar answered Jul 17 '26 23:07

JLavoie



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!