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!
Top comments (4)
When we parse the JSON, the "undefined" properties get removed automatically.
This is true. Thanks for sharing.
Nested objects?
The validate method below cleans the object/object literal if object is nested/complex.
If used the below sample
It modifies the object to the below result