javascript 如何删除空值对象中的键?

50few1ms  于 2023-01-07  发布在  Java
关注(0)|答案(6)|浏览(311)

我有这样一个目标:

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

我需要删除此对象中值为空的所有键/值对,例如''
因此,在上述情况下应删除caste: ''属性。
我试过:

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

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

v9tzhpje

v9tzhpje1#

你可以使用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>
brvekthn

brvekthn2#

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

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

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

〈---之后仅显示C

newObj = { c: 'hello world' }

基本上拒绝就像过滤器,但不包括结果。做过滤器(不(...),项目)如果我的任何条件通过它将拒绝特定的关键字。
希望能帮上忙!

webghufk

webghufk3#

你可以使用纯javascript吗?(没有Ramda)
如果确实需要从对象中删除属性,可以使用delete operator

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

如果您喜欢一行程序:

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

bsxbgnwa4#

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

anhgbhbe5#

如果你想要一个纯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
}), {});
gmxoilav

gmxoilav6#

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

相关问题