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:
xxxxxxxxxx
1
function removeEmptyValues(object) {
2
for (var key in object) {
3
if (object.hasOwnProperty(key)) {
4
var value = object[key];
5
if (value === null || value === undefined || value === '') {
6
delete object[key];
7
}
8
}
9
}
10
}
11
12
13
// Usage example:
14
15
var student = {
16
name: 'John',
17
age: undefined,
18
type: null,
19
comment: ''
20
};
21
22
console.log(JSON.stringify(student)); // {"name":"John","type":null,"comment":""}
23
24
removeEmptyValues(student);
25
26
console.log(JSON.stringify(student)); // {"name":"John"}
xxxxxxxxxx
1
const removeEmptyValues = (object) => {
2
const keys = Object.keys(object);
3
for (var i = 0; i < keys.length; ++i) {
4
const key = keys[i];
5
const value = object[key];
6
if (value === null || value === undefined || value === '') {
7
delete object[key];
8
}
9
}
10
};
11
12
13
// Usage example:
14
15
const student = {
16
name: 'John',
17
age: undefined,
18
type: null,
19
comment: ''
20
};
21
22
console.log(JSON.stringify(student)); // {"name":"John","type":null,"comment":""}
23
24
removeEmptyValues(student);
25
26
console.log(JSON.stringify(student)); // {"name":"John"}