DEV Community

Cover image for Cleaning an object
sndp
sndp

Posted on

Cleaning an object

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!

Top comments (4)

Collapse
 
codecraftjs profile image
Code Craft-Fun with Javascript

When we parse the JSON, the "undefined" properties get removed automatically.

const obj = {a: undefined, b: "test", c: null, d: false, e: 0};
console.log(JSON.parse(JSON.stringify(obj)))
// {b: 'test', c: null, d: false, e: 0}
Enter fullscreen mode Exit fullscreen mode
Collapse
 
lizardkinglk profile image
sndp • Edited

This is true. Thanks for sharing.

Collapse
 
jonrandy profile image
Jon Randy 🎖️

Nested objects?

Collapse
 
lizardkinglk profile image
sndp • Edited

The validate method below cleans the object/object literal if object is nested/complex.

const validate = (obj) => {
    for (const i in obj) {
        if ([null, undefined, ""].includes(obj[i])) {
            delete obj[i];
        }
        if (typeof obj[i] !== "string") {
            validate(obj[i]);
        }
        if (Array.isArray(obj[i])) {
            obj[i] = obj[i].filter(j => Boolean(j));
        }
    }
};
Enter fullscreen mode Exit fullscreen mode

If used the below sample

const obj = {
    "foo": "",
    "bar": null,
    "max": undefined,
    "firstName": "John",
    "lastName": "Doe",
    "age": 42,
    "children": [
        null,
        undefined,
        "",
        {
            "foo": "",
            "bar": null,
            "max": undefined,
            "firstName": "Jack",
            "lastName": "Doe",
            "age": 24,
            "children": null
        },
        {
            "firstName": "Jane",
            "car": {},
            "children": [],
            "isMarried": 0
        },
    ]
};
Enter fullscreen mode Exit fullscreen mode

It modifies the object to the below result

{
  "firstName": "John",
  "lastName": "Doe",
  "age": 42,
  "children": [
    { "firstName": "Jack", "lastName": "Doe", "age": 24 },
    { "firstName": "Jane", "car": {}, "children": [], "isMarried": 0 }
  ]
}
Enter fullscreen mode Exit fullscreen mode