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

Viewed 9864

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?

5 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>

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!

Are you ok to use pure javascript for this ? (no Ramda)

If you really need to remove a property from an object, you can use delete operator.

for (const key in obj) {
    if (obj[key] === "") {
        delete obj[key];
    }
}

If you prefer one-liner :

Object.entries(obj).forEach(e => {if (e[1] === "") delete obj[e[0]]});
reject(complement(identity))
({
  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
})


{"matrimonyUrl": "christian-grooms",
"religion": "Christian", 
"search_criteria": "a:2:{s:6:\"gender\";s:4:\"Male\";s:9:\"community\";s:9:\"Christian\";}"
}
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);
Related