Compact object

OSCC · JavaScript, Object, Array, Recursion · Nov 27, 2020

Deeply removes all falsy values from an object or array.

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' } }

Recommended snippets

  • Object to entries

    JavaScript, Object

    Creates an array of key-value pair arrays from an object.

  • Object to pairs

    JavaScript, Object

    Creates an array of key-value pair arrays from an object or other iterable.

  • Unwind object

    JavaScript, Object

    Produces an array of objects from an object and one of its array-valued properties.