nodejs remove null from object

Node.js: Removing Null from Object

As a developer, you may need to remove any null properties from an object in Node.js. This can be achieved easily with built-in functions of JavaScript.

Method 1: Using delete operator

You can use the delete operator to remove the null values from an object. This method will delete the property from the object if it has a value of null or undefined. Here's an example:


            let obj = {
                name: "John",
                age: null,
                address: {
                    city: "New York",
                    state: null,
                    country: "USA"
                }
            };

            for (let prop in obj) {
                if (obj[prop] == null) {
                    delete obj[prop];
                } else if (typeof obj[prop] === "object") {
                    for (let nestedProp in obj[prop]) {
                        if (obj[prop][nestedProp] == null) {
                            delete obj[prop][nestedProp];
                        }
                    }
                }
            }

            console.log(obj);
        

In this example, we are using a for loop to iterate over each property of the object. If a property has a value of null, we are deleting that property using the delete operator. If a property is an object, we use another for loop to iterate over its nested properties and delete any null values.

Method 2: Using Object.entries() and reduce()

You can also use the Object.entries() method to convert the object into an array of key-value pairs and then use the reduce() method to create a new object without null values. Here's an example:


            let obj = {
                name: "John",
                age: null,
                address: {
                    city: "New York",
                    state: null,
                    country: "USA"
                }
            };

            let newObj = Object.entries(obj).reduce((acc, [key, value]) => {
                if (value !== null) {
                    if (typeof value === "object") {
                        acc[key] = removeNull(value);
                    } else {
                        acc[key] = value;
                    }
                }

                return acc;
            }, {});

            console.log(newObj);
        

In this example, we are using Object.entries() to convert the object into an array of key-value pairs. Then we use the reduce() method to iterate over each key-value pair and create a new object without null values. If a value is an object, we recursively call the function to remove null values from nested objects.

Both methods are effective in removing null values from an object in Node.js. Choose the one that suits your needs best.

Subscribe to The Poor Coder | Algorithm Solutions

Don’t miss out on the latest issues. Sign up now to get access to the library of members-only issues.
[email protected]
Subscribe