4

I want to remove all null values from a object. Let's suppose:

const data = {
  key1: 'ok',
  key2: null,
  key3: '', // should be removed too
  key4: {
    inner_key1: 'aaa',
    inner_key2: null
  }
}

What I did was this

const clean = R.reject(R.either(R.isNil, R.isEmpty))

And this work:

{"key1":"ok","key4":{"inner_key1":"aaa","inner_key2":null}}

Except for nested objects, as you can see, inner_key2 is present, and should be filtered out.

Using ramda, how can I remove this nested values too?

Rodrigo
  • 135
  • 4
  • 45
  • 107

1 Answers1

5

Create a recursive function that iterates the properties after cleaning the object, and calls clean on each property, which is an object:

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

const clean = o => pipe(
  reject(either(isNil, isEmpty)),
  map(when(is(Object), clean))
)(o)

const data = {"key1":"ok","key2":null,"key3":"","key4":{"inner_key1":"aaa","inner_key2":null}}
const result = clean(data)

console.log(result)
<script src="https://cdnjs.cloudflare.com/ajax/libs/ramda/0.27.1/ramda.js" integrity="sha512-3sdB9mAxNh2MIo6YkY05uY1qjkywAlDfCf5u1cSotv6k9CZUSyHVf4BJSpTYgla+YHLaHG8LUpqV7MHctlYzlw==" crossorigin="anonymous"></script>
Ori Drori
  • 183,571
  • 29
  • 224
  • 209
  • 1
    That's very nice. I usually suggest that Ramda isn't designed around -- or particularly well-suited for -- recursive tasks. But code like this makes me rethink that statement. – Scott Sauyet May 12 '21 at 17:45