Cleaning an object

sndp - Jul 3 '23 - - Dev Community

Let's say we have a javascript object or JSON object literal that we use to do some task. And let's say those object values weren't predicted which means it can cause problems in the task execution due to nullish values. These nullish values may consist of the follwing.

undefined, null, ""
Enter fullscreen mode Exit fullscreen mode

Our goal is to change the given object to a clean record.

suspended bridge , Pakding, Nepal
Photo by Sebastian Pena Lambarri

Let's assume we are given the following object.

const obj = {
    "foo": "",
    "bar": null,
    "max": undefined,
    "firstName": "John",
    "lastName": "Doe",
    "age": 42
};
Enter fullscreen mode Exit fullscreen mode

Points to consider

  1. The for-in loop takes an object and makes it an iterable of keys. In other words it returns the indexes/keys of that object. We can use this to iterate the object and access each element.

  2. The built-in function includes uses to check if an element contains in the given array. In here we are using it to check if the value given available within the items we have.

  3. The operator/function delete removes an element/value by the key of the object given.

How to do it

With this below function we can achieve our goal.

for (const i in obj) {
    if ([null, undefined, ""].includes(obj[i])) {
        delete obj[i];
    }
}
Enter fullscreen mode Exit fullscreen mode

This function demonstrates the points mentioned above. It iterates the object via the keys (for-in loop) and checks the value contains in the array given (includes). If so it removes the key-value pair from the object (delete).

Finally we are left with the object containing clean values.

{ firstName: 'John', lastName: 'Doe', age: 42 }
Enter fullscreen mode Exit fullscreen mode

Thanks for reading!

. . . . . . . . . . . . . . . . . . . .
Terabox Video Player