How do I remove all attributes which are undefined
or null
in a JavaScript object?
(Question is similar to this one for Arrays)
A simple one-liner (returning a new object).
let o = Object.fromEntries(Object.entries(obj).filter(([_, v]) => v != null));
Same as above but written as a function.
function removeEmpty(obj) { return Object.fromEntries(Object.entries(obj).filter(([_, v]) => v != null)); }
This function uses recursion to remove items from nested objects.
function removeEmpty(obj) { return Object.fromEntries( Object.entries(obj) .filter(([_, v]) => v != null) .map(([k, v]) => [k, v === Object(v) ? removeEmpty(v) : v]) ); }
A simple one-liner. Warning: This mutates the given object instead of returning a new one.
Object.keys(obj).forEach((k) => obj[k] == null && delete obj[k]);
A single declaration (not mutating the given object).
let o = Object.keys(obj) .filter((k) => obj[k] != null) .reduce((a, k) => ({ ...a, [k]: obj[k] }), {});
Same as above but written as a function.
function removeEmpty(obj) { return Object.entries(obj) .filter(([_, v]) => v != null) .reduce((acc, [k, v]) => ({ ...acc, [k]: v }), {}); }
This function uses recursion to remove items from nested objects.
function removeEmpty(obj) { return Object.entries(obj) .filter(([_, v]) => v != null) .reduce( (acc, [k, v]) => ({ ...acc, [k]: v === Object(v) ? removeEmpty(v) : v }), {} ); }
Same as the function above, but written in an imperative (non-functional) style.
function removeEmpty(obj) { const newObj = {}; Object.entries(obj).forEach(([k, v]) => { if (v === Object(v)) { newObj[k] = removeEmpty(v); } else if (v != null) { newObj[k] = obj[k]; } }); return newObj; }
In the old days things were a lot more verbose.
This is a non recursive version written in a functional style.
function removeEmpty(obj) { return Object.keys(obj) .filter(function (k) { return obj[k] != null; }) .reduce(function (acc, k) { acc[k] = obj[k]; return acc; }, {}); }
This is a non recursive version written in an imperative style.
function removeEmpty(obj) { const newObj = {}; Object.keys(obj).forEach(function (k) { if (obj[k] && typeof obj[k] === "object") { newObj[k] = removeEmpty(obj[k]); } else if (obj[k] != null) { newObj[k] = obj[k]; } }); return newObj; }
And a recursive version written in a functional style.
function removeEmpty(obj) { return Object.keys(obj) .filter(function (k) { return obj[k] != null; }) .reduce(function (acc, k) { acc[k] = typeof obj[k] === "object" ? removeEmpty(obj[k]) : obj[k]; return acc; }, {}); }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With