Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ramda: How to remove keys in objects with empty values?

I have this object:

let obj = {
  matrimonyUrl: 'christian-grooms',
  search_criteria:
    'a:2:{s:6:"gender";s:4:"Male";s:9:"community";s:9:"Christian";}',
  mothertongue: null,
  religion: 'Christian',
  caste: '',
  country: null
};

I need to remove all key/value pairs in this object where the value is blank i.e. ''

So the caste: '' property should be removed in the above case.

I have tried:

R.omit(R.mapObjIndexed((val, key, obj) => val === ''))(obj);

But this doesn't do anything. reject doesn't work either. What am I doing wrong?

like image 644
Amit Erandole Avatar asked Jun 16 '19 10:06

Amit Erandole


People also ask

Is ramda better than Lodash?

Ramda is generally a better approach for functional programming as it was designed for this and has a community established in this sense. Lodash is generally better otherwise when needing specific functions (esp. debounce ).

Should I use ramda?

Yep. Ramda is an excellent library for getting started on thinking functionally with JavaScript. Ramda provides a great toolbox with a lot of useful functionality and decent documentation. If you'd like to try the functionality as we go, check out Ramda's REPL.

What is compose in ramda?

compose FunctionPerforms right-to-left function composition. The rightmost function may have any arity; the remaining functions must be unary. See also pipe.


2 Answers

You can use R.reject (or R.filter) to remove properties from an object using a callback:

const obj = {
  matrimonyUrl: 'christian-grooms',
  search_criteria:
    'a:2:{s:6:"gender";s:4:"Male";s:9:"community";s:9:"Christian";}',
  mothertongue: null,
  religion: 'Christian',
  caste: '',
  country: null
};

const result = R.reject(R.equals(''))(obj);

console.log(result);
<script src="https://cdnjs.cloudflare.com/ajax/libs/ramda/0.26.1/ramda.js"></script>
like image 76
Ori Drori Avatar answered Oct 25 '22 05:10

Ori Drori


I did it like that, but I was also needed to exclude the nullable values, not only the empty one.

const obj = { a: null, b: '',  c: 'hello world' };

const newObj = R.reject(R.anyPass([R.isEmpty, R.isNil]))(obj);

< --- only C going to display after

newObj = { c: 'hello world' }

Basically Reject is like filter but not include the results. doing filter(not(....), items) If any of my conditions pass it will reject the specific key.

Hope It's helps!

like image 23
Ido Bleicher Avatar answered Oct 25 '22 06:10

Ido Bleicher