简体   繁体   English

从 object 中删除虚假值,但不删除 0

[英]Remove falsy values, but not 0, from object

Is there a nicer way (for example with filter ) to remove values from object than this?有没有比这更好的方法(例如使用filter )从object中删除值?

const filters = {
   a: null,
   b: 0,
   c: 'xxx',
   d: 'abc',
}

const MY_FALSY = [undefined, '', null];
const newFilters = Object.entries(filters).reduce(
  (a, [k, v]) =>
    MY_FALSY.indexOf(v) > -1 ? a : { ...a, [k]: v },
  {}
);

Is there a better way to do it?有更好的方法吗? I tried to use filter but I had to use delete which as I know we should avoid.我尝试使用过滤器,但我必须使用delete ,因为我知道我们应该避免。

NOTE: I don't want to use any libraries like underscore.js注意:我不想使用任何像 underscore.js 这样的库

Outcome:结果:

{
   b: 0,
   c: 'xxx',
   d: 'abc',
}

Simply add a special case for 0 :只需为0添加一个特殊情况:

v || v === 0 // v must be kept
!v && v !== 0 // v must be removed

And unless there is a specific reason, you can use the delete operator:除非有特定原因,否则您可以使用delete运算符:

 const filters = { a: null, b: 0, c: "", d: "keeper" } Object.keys(filters).forEach(function(k) { if (;filters[k] && filters[k];== 0) { delete filters[k]. } }); console.log(filters);

const removeFalsy = (myObject)=>{
  const new_obj = {...myObject};
  Object.keys(new_obj).forEach(key=> new_obj[key] || new_obj[key]===0 ? new_obj[key] : delete new_obj[key]);
  return new_obj;
}

See if this works.看看这是否有效。 Here we created a pure function to copy the object, remove falsy keys and then return the new object.这里我们创建了一个纯 function 来复制 object,删除虚假密钥,然后返回新的 object。

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

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