Hello Friends 👋,
Welcome to Infinitbility.
When we got objects from the server or API sometime’s we get keys with null or undefined values and it will throw an error when we use them blindly.
I.e we will learn how to delete keys that have null, or undefined values.
To remove javascript falsy values we used javascript Object.keys(), forEach() or for loop, and delete operator.
- javascript
Object.keys()method to get an array of the object’s keys. forEach()orforloop to check every keys in object.deleteoperator to remove key values from the object.
JavaScript forEach loop example to remove null, or undefined values
const obj = {
id: 1,
name: "infinitbility",
age: null,
waight: undefined,
isActive: false,
};
Object.keys(obj).forEach(key => {
if (obj[key] === null || obj[key] === undefined) {
delete obj[key];
}
});
console.log(obj); // { id: 1, name: 'infinitbility', isActive: false }
Output
JavaScript for loop example to remove null, or undefined values
Using for loop we will bypass the Object.keys() method and let’s take an example.
const obj = {
id: 1,
name: "infinitbility",
age: null,
waight: undefined,
isActive: false,
};
for (const key in obj) {
if (obj[key] === null || obj[key] === undefined) {
delete obj[key];
}
}
console.log(obj); // { id: 1, name: 'infinitbility', isActive: false }
Output
Thanks for reading…