1

Similar to Ramda: How to remove keys in objects with empty values? but I am looking for something that works recursively. This is so I can workaround a "feature" of AJV and JSON Schema where null !== undefined.

I started with this... which is to remove the nulls but does not work recursively

import R from 'ramda';
describe('filter null values', () => {
  it('should filter out null values', () => {
    const specimen = {
      tasks: [
        { id: 'foo', blank: '', zero: 0, nool: null },
        { nool: null },
        { id: '', blank: null, zero: 0, nool: null },
      ],
      useless: { nool: null },
      uselessArray: [{ nool: null }],
      nool: null,
    };
    const expectation = {
      tasks: [
        { id: 'foo', blank: '', zero: 0 },
        { id: '', zero: 0 },
      ],
    };
    const removeNulls = R.reject(R.equals(null));
    expect(removeNulls(specimen)).toEqual(expectation);
  });
});

Archimedes Trajano
  • 35,625
  • 19
  • 175
  • 265

1 Answers1

1

Map the passed item. If the value is an Object (or Array), recursively call removeNulls on the current value. After mapping the values, reject all undefined, null, or empty non string values (see R.isEmpty).

const { pipe, map, when, is, reject, ifElse, F, either, isEmpty, isNil } = R;

const removeNulls = pipe(
  map(when(is(Object), v => removeNulls(v))),
  reject(ifElse(is(String), F, either(isEmpty, isNil))),
);

const specimen = {"tasks":[{"id":"foo","blank":"","zero":0,"nool":null},{"nool":null},{"id":"","blank":null,"zero":0,"nool":null}],"useless":{"nool":null},"uselessArray":[{"nool":null}],"nool":null};

const result = removeNulls(specimen);

console.log(result);
<script src="https://cdnjs.cloudflare.com/ajax/libs/ramda/0.27.1/ramda.min.js" integrity="sha512-rZHvUXcc1zWKsxm7rJ8lVQuIr1oOmm7cShlvpV0gWf0RvbcJN6x96al/Rp2L2BI4a4ZkT2/YfVe/8YvB2UHzQw==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>
Ori Drori
  • 183,571
  • 29
  • 224
  • 209