Remove Null And Undefined Values From Object

In this article, we will discuss how to check for null or undefined values inside an object and remove them. This technique involves iterating over the object values, checking for null or undefined conditions, and utilizing the delete operator to remove the corresponding properties.

Remove Null And Undefined Values From Object

First, we will create our object and initialize it with values –

const obj = {

  key1: "value1",

  key2: "",

  key3: "value3",

  key4: null,

  key5: "value5",

  key6: undefined

};

Our objective is to iterate over the object’s keys, check the corresponding values, and remove any properties that have null or undefined values. We can achieve this by using a for..in loop, which allows us to loop through all the enumerable properties of an object. This loop provides a concise solution with fewer lines of code.

Using for..in loop

Let’s implement the removal of null and undefined values using a for..in loop:

for (const key in obj) {

if (obj[key] === null || obj[key] === undefined) delete obj[key];

}

In the code snippet above, we iterate over each key in the obj object. If the corresponding value is null or undefined, we use the delete operator to remove the property from the object.

However, it’s important to note that in addition to checking for null and undefined, you mentioned that you also don’t want empty strings ("") unless they are required for a specific scenario. To handle this requirement, we can encapsulate the condition within a function called checkInvalidValue. This function takes a value as an argument and checks if it is null, undefined, or an empty string. It returns true if the condition matches, indicating that the value should be removed.

Remove All Invalid Values

Let’s define the checkInvalidValue function:

const checkInvalidValue = (value) => {
  if (value === null || value === undefined || value === "") {
    return true;
  } else {
    return false;
  }
};

Now, we can modify our for..in loop to utilize the checkInvalidValue function and remove the properties accordingly:

for (const key in obj) {
  if (checkInvalidValue(obj[key])) {
    delete obj[key];
  }
}

By incorporating the checkInvalidValue function, we ensure that properties with null, undefined, and empty string values are all removed from the object.

To verify the result, we can log the modified object to the console:

console.log(obj);
null and undefined values got removed from object

When executing the code, you will observe that the properties key2, key4, and key6 have been successfully removed from the object.

Conclusion

In conclusion, by utilizing JavaScript’s for..in loop, along with the delete operator and the checkInvalidValue function, we can effectively check for null or undefined values inside an object and remove them. This approach allows us to maintain cleaner and more streamlined data structures in our JavaScript applications.

Leave a Reply