compactObject
Deeply removes all falsy values from an object or array.
- Use recursion.
- Initialize the iterable data, using
Array.isArray()
,Array.prototype.filter()
andBoolean
for arrays in order to avoid sparse arrays. - Use
Object.keys()
andArray.prototype.reduce()
to iterate over each key with an appropriate initial value. - Use
Boolean
to determine the truthiness of each key's value and add it to the accumulator if it's truthy. - Use
typeof
to determine if a given value is anobject
and call the function again to deeply compact it.
const compactObject = val => {
const data = Array.isArray(val) ? val.filter(Boolean) : val;
return Object.keys(data).reduce(
(acc, key) => {
const value = data[key];
if (Boolean(value))
acc[key] = typeof value === 'object' ? compactObject(value) : value;
return acc;
},
Array.isArray(val) ? [] : {}
);
};