mirror of
https://github.com/Fechin/reference.git
synced 2026-11-21 21:44:45 +03:00
1.0 KiB
1.0 KiB
title, tags, layout
| title | tags | layout | |||||
|---|---|---|---|---|---|---|---|
| How to remove all null and undefined properties from an object in JavaScript |
|
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 }