Strip Null And Empty Fields With Entries And FromEntries
A recursive pass over Object.entries and Object.fromEntries drops null, undefined and empty-string fields before persistence while keeping 0 and false intact.
Code
// Plain JSON data only: recursively drop null, undefined and empty strings,
// while 0 and false must survive because they are real values
const strip = (value) => {
if (Array.isArray(value)) {
return value
.map(strip)
.filter((item) => item !== null && item !== undefined && item !== '');
}
if (value !== null && typeof value === 'object') {
return Object.fromEntries(
Object.entries(value)
.filter(([, v]) => v !== null && v !== undefined && v !== '')
.map(([key, v]) => [key, strip(v)]),
);
}
return value;
};
const payload = {
id: 'a1',
note: null,
meta: { retry: 0, archived: false, label: undefined, tags: ['x', '', null, 'y'] },
};
console.log(strip(payload));
console.log(JSON.stringify(strip(payload)));Output
Captured from a sandboxed run of this snippet in the build pipeline.
{ id: 'a1', meta: { retry: 0, archived: false, tags: [ 'x', 'y' ] } }
{"id":"a1","meta":{"retry":0,"archived":false,"tags":["x","y"]}}What the demo strips
strip walks payloads recursively: arrays map then filter, plain objects go through Object.entries, filter out null, undefined and empty strings, then rebuild with Object.fromEntries. Inside meta, the retry 0 and archived false survive because they are real values.
The tags array loses its empty string and null entries but keeps x and y, and the nested label: undefined disappears from the printed JSON. Scalars pass through untouched, so the id and the cleaned meta structure are the only visible changes.
Practical notes
- 0 and false must survive the filter; they are meaningful values.
- Arrays and objects get the same rule applied one level at a time.
Interactive Tools for This Topic
FAQ
- Why keep 0 and false while dropping empty strings?
- 0 and false carry meaning for persistence; an empty string is treated as absent. The filter list is explicit: null, undefined and the empty string only.
Report a problem with this exampleOpens a pre-filled issue on GitHub.