在javascript中,有没有一种好方法可以从javascript对象(而不是数组)中删除Falsy值? [英] Is there a nice way in javascript to removing Falsy values from a javascript object (not an array)?

查看:35
本文介绍了在javascript中,有没有一种好方法可以从javascript对象(而不是数组)中删除Falsy值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在JavaScript中,您可以使用漂亮的.filter方法从数组中删除null或falsy值.到目前为止,我还没有找到一种从JavaScript对象中删除相同方法的方法.

In JavaScript you have the nice .filter method to remove null or falsy values from arrays. So far I haven't been able to find a method to remove the same from JavaScript Objects.

为什么会这样?

当前,您可以为数组创建函数,如:

Currently you can create a function for arrays like :

function stripNulls(arr) {
   return arr.filter(Boolean);
}

是否可以为JS对象创建类似的功能,或者过滤器在JS对象上不可行.

Is there a similar function that can be created for JS Objects, or is the way filter works not practical on JS Objects.

推荐答案

我可以对对象做x"(或针对该对象的数组)的答案通常是是",并且通常涉及某种形式的reduce.

The answer to "can I do x to an object" (or an array for that matter) is usually "yes" and it frequently involves some form of reduce.

如果要过滤虚假值,可以执行以下操作:

If you want to filter falsy values you could do something like this:

function filterFalsy(obj) {
  return Object.keys(obj).reduce((acc, key) => {
    if (obj[key]) {
      acc[key] = obj[key]
    }

    return acc
  }, {})
}

const testObj = {
  a: 'test',
  b: 321,
  c: false
}

console.log(filterFalsy(testObj))

这将返回一个没有伪造值的新对象,并将现有对象保留下来.

This returns a new object without falsy values and leaves the existing object alone.

这篇关于在javascript中,有没有一种好方法可以从javascript对象(而不是数组)中删除Falsy值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆