根据值过滤对象属性 [英] Filtering object properties based on value

查看:60
本文介绍了根据值过滤对象属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否有一些优雅的方法可以使用lodash / underscore从此对象中过滤出虚假属性?类似于 _。compact(array)从数组中删除falsey元素

Is there some elegant way of filtering out falsey properties from this object with lodash/underscore? Similar to how _.compact(array) removes falsey elements from arrays

所以从

{
  propA: true,
  propB: true,
  propC: false,
  propD: true,
}

返回

{
  propA: true,
  propB: true,
  propD: true,
}


推荐答案

在Lodash 4.0之前



你想要的 _。选择,它接受一个函数作为参数,并返回一个只包含该函数返回truthy的键的对象。所以你可以这样做:

Prior to Lodash 4.0

You want _.pick, it takes a function as an argument and returns an object only containing the keys for which that function returns truthy. So you can do:

filtered = _.pick(obj, function(value, key) {return value;})

或者更简洁:

filtered = _.pick(obj, _.identity)



Lodash 4.0



Lodash 4.0将 _。pick 功能拆分为 _。pick ,它接受一系列属性, _。pickBy 接受一个函数。所以现在它是

Lodash 4.0

Lodash 4.0 split the _.pick function into _.pick, which takes an array of properties, and _.pickBy which takes a function. So now it'd be

filtered = _.pickBy(obj, function(value, key) {return value;})

或者,因为 _。pickBy 默认为使用 _。identity 作为它的第二个参数,它可以写成:

Or, since _.pickBy defaults to using _.identity as it's second argument, it can just be written as:

filtered = _.pickBy(obj);

这篇关于根据值过滤对象属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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