繁体   English   中英

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

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

我有这个 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
};

我需要删除此 object 中值为空白的所有键/值对,即''

因此在上述情况下应删除caste: ''属性。

我努力了:

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

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

您可以使用R.reject (或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 = { a: null, b: '',  c: 'hello world' };

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

< --- 只有 C 将在之后显示

newObj = { c: 'hello world' }

基本上拒绝就像过滤器但不包括结果。 做 filter(not(....), items) 如果我的任何条件通过,它将拒绝特定的键。

希望它有帮助!

您可以为此使用纯 javascript 吗? (没有拉姆达)

如果您确实需要从对象中删除属性,则可以使用delete 运算符

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

如果您更喜欢单线:

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

如果你想要一个纯粹的 javascript 答案:

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

// Iterate over obj keys
const newObj = Object.keys(obj).reduce((acc, key) => ({
  // Return the accumulator obj on every iteration
  ...acc,
  // Decide if we want to return the current {key:value} pair 
  ...(obj[key] !== '' ? { [key]: obj[key] } : {}),
// Initialize the accumulator obj
}), {});
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);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM