Files
reference/source/_posts/note/javascript/object/remove-all-null-and-undefined-properties-from-an-object.md
T
2022-11-16 14:10:09 +08:00

1.0 KiB

title, tags, layout
title tags layout
How to remove all null and undefined properties from an object in JavaScript
JavaScript
ES6
one-line
js
Object
note

In this Article we will go through how to remove all null and undefined properties from an object only using single line of code in JavaScript. This is a one-line JavaScript code snippet that uses one of the most popular ES6 features => Arrow Function.

Let's define this short function:

const removeNullUndefined = obj => Object.entries(obj).reduce((a, [k, v]) => (v == null ? a : (a[k] = v, a)), {});

Or

const removeNullUndefined = obj => Object.entries(obj).filter(([_, v]) => v != null).reduce((acc, [k, v]) => ({ ...acc, [k]: v }), {});

Or

const removeNullUndefined = obj => Object.fromEntries(Object.entries(obj).filter(([_, v]) => v != null));

Example

removeNullUndefined({
    foo: null,
    bar: undefined,
    fuzz: 42,
});                         // { fuzz: 42 }