Remove all null and undefined properties from an object
Drop keys whose value is null or undefined.
function removeNullish(object) { return Object.fromEntries(Object.entries(object).filter(([, value]) => value != null)); }
Input & expected output
Input
{
"to": "[email protected]",
"cc": null,
"subject": "Order 8812",
"templateId": null
}Expected output
{
"to": "[email protected]",
"subject": "Order 8812"
}The edge case
Input
{
"a": 0,
"b": "",
"c": false
}Expected output
{
"a": 0,
"b": "",
"c": false
}Know the limits
- Only null and undefined are removed: 0, "" and false stay, as the edge case shows.
- Shallow: nested objects keep their nulls.
The function above is the implementation used by the lab. The lab validates JSON types and caps size before execution; include equivalent validation when accepting untrusted input in your application.
Source & maintenance
Based on Remove all null and undefined properties from an object from the original 1loc collection by Nguyen Huu Phuoc, with jjswifty. Copyright (c) 2020 phuoc-ng. MIT licensed.
Keeps the filter variant with Object.fromEntries. Original MDX retained as inert source evidence.
Maintained by Oveyon. Source commit: 14b481cf60df. Read the license.
Keep exploring
- Pick properties from an object — Build a new object with only the requested own properties.
- Omit properties from an object — Keep the own enumerable fields that are not in a supplied list.
- Create an object from pairs of key and value — Turn [key, value] pairs into a plain object with Object.fromEntries.