EN
JavaScript - remove empty values from object
3
points
In this article, we would like to show you how to remove empty values from object in JavaScript.
Quick solution:
// ONLINE-RUNNER:browser;
function removeEmptyValues(object) {
for (var key in object) {
if (object.hasOwnProperty(key)) {
var value = object[key];
if (value === null || value === undefined || value === '') {
delete object[key];
}
}
}
}
// Usage example:
var student = {
name: 'John',
age: undefined,
type: null,
comment: ''
};
console.log(JSON.stringify(student)); // {"name":"John","type":null,"comment":""}
removeEmptyValues(student);
console.log(JSON.stringify(student)); // {"name":"John"}
Alternative solution
// ONLINE-RUNNER:browser;
const removeEmptyValues = (object) => {
const keys = Object.keys(object);
for (var i = 0; i < keys.length; ++i) {
const key = keys[i];
const value = object[key];
if (value === null || value === undefined || value === '') {
delete object[key];
}
}
};
// Usage example:
const student = {
name: 'John',
age: undefined,
type: null,
comment: ''
};
console.log(JSON.stringify(student)); // {"name":"John","type":null,"comment":""}
removeEmptyValues(student);
console.log(JSON.stringify(student)); // {"name":"John"}