compactObject
Deeply removes all falsy values from an object or array.
- Use recursion.
- Initialize the iterable data, using
Array.isArray(),Array.prototype.filter()andBooleanfor arrays in order to avoid sparse arrays. - Use
Object.keys()andArray.prototype.reduce()to iterate over each key with an appropriate initial value. - Use
Booleanto determine the truthiness of each key's value and add it to the accumulator if it's truthy. - Use
typeofto determine if a given value is anobjectand 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) ? [] : {}
);
};