1.3 KiB
1.3 KiB
title, tags, cover, firstSeen, lastUpdated
| title | tags | cover | firstSeen | lastUpdated |
|---|---|---|---|---|
| Compact object | object,array,recursion | shapes | 2020-11-27T13:57:41+02:00 | 2020-11-27T13:57:41+02:00 |
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) ? [] : {}
);
};
const obj = {
a: null,
b: false,
c: true,
d: 0,
e: 1,
f: '',
g: 'a',
h: [null, false, '', true, 1, 'a'],
i: { j: 0, k: false, l: 'a' }
};
compactObject(obj);
// { c: true, e: 1, g: 'a', h: [ true, 1, 'a' ], i: { l: 'a' } }