EN
JavaScript - removing undefined fields from object
1 answers
0 points
How can I remove properties from object that are undefined
or null
?
1 answer
0 points
Quick solution (ES6+):
xxxxxxxxxx
1
const newObject = Object.fromEntries(Object.entries(myObject).filter(([_, value]) => value != null));
Reusable arrow function
xxxxxxxxxx
1
const removeBlank = (inputObject) => {
2
return Object.fromEntries(
3
Object.entries(inputObject).filter(([_, value]) => value != null)
4
);
5
}
6
7
8
// Usage example:
9
10
const myObject = { a: 1, b: '', c: undefined, d: null };
11
12
const newObject = removeBlank(myObject);
13
14
console.log(JSON.stringify(newObject)); // { a: 1, b: '' }
Explanation:
To remove properties that are undefined
or null
we used the following methods:
Object.entries()
- to get array of a given object's properties ([key, value]
pairs),filter()
- to remove properties that values arenull
orundefined
,Object.fromEntries()
- to create a new result object from filtered[key, value]
pairs.
Recursion to remove properties from nested objects
xxxxxxxxxx
1
const removeBlank = (inputObject) => {
2
return Object.fromEntries(
3
Object.entries(inputObject)
4
.filter(([_, value]) => value != null)
5
.map(([key, value]) => [
6
key,
7
value === Object(value) ? removeBlank(value) : value,
8
])
9
);
10
};
11
12
13
// Usage example:
14
15
const myObject = {
16
a: 1,
17
b: { b1: undefined },
18
c: { c1: null },
19
};
20
21
const newObject = removeBlank(myObject);
22
23
console.log(JSON.stringify(newObject, null, 4)); // { a: 1, b: {}, c: {} }
References
0 commentsShow commentsAdd comment