Cleaning an object
sndp
Posted on July 3, 2023
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, ""
Our goal is to change the given object to a clean record.
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
};
Points to consider
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.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.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];
}
}
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 }
Thanks for reading!
Posted on July 3, 2023
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.
Related
November 3, 2024
September 15, 2024