Deep-remove falsy values from nested arrays and objects
Before a settings form is saved, the client strips out every field the user left blank so the API only receives meaningful data. Blank fields can appear at any depth: inside nested sections, inside lists, inside objects in lists.
Implement pruneFalsy(value, options). It returns a deep copy of value with every falsy value removed from every array and plain object.
pruneFalsy(value, options?) // => pruned copy of value
// options: { removeEmpty?: boolean } (default false)
false, 0, -0, 0n, '', null, undefined, and NaN.Object.prototype or null): remove every own enumerable key (Object.keys) whose value is falsy. Keep the remaining keys in their original order.Date, a Map, a class instance, a function) is kept as is, by reference, and is not looked inside.{ removeEmpty: true }, an array or plain object that is empty after pruning is removed from its parent as well. This can cascade upward.pruneFalsy([0, 'tea', '', null, 3, NaN, false]);
// => ['tea', 3]
const profile = {
name: 'Noor',
nickname: '',
age: 0,
links: ['https://noor.dev', null, ''],
address: { line1: '12 Quay St', line2: undefined, postcode: '' },
newsletter: false,
};
pruneFalsy(profile);
// => {
// name: 'Noor',
// links: ['https://noor.dev'],
// address: { line1: '12 Quay St' },
// }
pruneFalsy({ billing: { vat: '' }, tags: [null, ''], plan: 'pro' });
// => { billing: {}, tags: [], plan: 'pro' }
pruneFalsy({ billing: { vat: '' }, tags: [null, ''], plan: 'pro' }, { removeEmpty: true });
// => { plan: 'pro' }
pruneFalsy({ draft: null }, { removeEmpty: true });
// => {} (the root is always returned)
pruneFalsy(0);
// => 0