Ramda:如何删除具有空值的对象中的键?

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

我有这个对象:

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

我需要删除此对象中值为空的所有 key/value 对,即 ''

所以在上面的例子中 caste: '' 属性 应该被删除。

我试过:

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

但这没有任何作用。 reject 也不行。我做错了什么?

您可以使用 R.reject (or R.filter) 通过回调从对象中删除属性:

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>

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

您可以为此使用纯 javascript 吗? (没有 Ramda)

如果你真的需要从一个对象中删除一个属性,你可以使用delete operator

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

如果你喜欢 one-liner :

Object.entries(obj).forEach(e => {if (e[1] === "") delete obj[e[0]]});

我就是这样做的, 但我还需要排除可空值,而不仅仅是空值。

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

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

< --- 在

之后只有 C 会显示
newObj = { c: 'hello world' }

基本上 Reject 就像过滤器一样,但不包括结果。做过滤器(不是(....),项目) 如果我的任何条件通过,它将拒绝特定密钥。

希望对您有所帮助!

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\";}"
}