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);
  });
});

0

1 Answer 1

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>

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.