You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用Lodash筛选canHaveCookie为true的父对象问题求助

正确的Lodash筛选实现方案

首先,你原来的代码里用_.includes(item, {canHaveCookie: true})是核心问题——_.includes是用来检测某个值是否存在于数组或者对象的值集合中,而你这里要判断的是每个子对象的canHaveCookie属性是否为true,不是要找整个{canHaveCookie: true}对象是否在子属性里。

下面是两种可行的正确实现方式:

方式一:直接在_.pickBy回调中判断属性值

const dataAttrObj = {
  name1: { canHaveCookie: true, anotherProp : false },
  name2: { canHaveCookie: false, anotherProp : false },
  name3: { canHaveCookie: true, anotherProp : false }
};

// 筛选出canHaveCookie为true的父对象
const filteredObj = _.pickBy(dataAttrObj, (item) => item.canHaveCookie === true);

console.log(filteredObj);
// 输出:{ name1: { canHaveCookie: true, anotherProp: false }, name3: { canHaveCookie: true, anotherProp: false } }

方式二:使用Lodash的_.matchesProperty快捷方法

如果你想更简洁,可以用_.matchesProperty来创建匹配器,它专门用来检测对象是否有指定的属性值:

const filteredObj = _.pickBy(dataAttrObj, _.matchesProperty('canHaveCookie', true));

这个效果和方式一完全一致,只是写法更简洁。

为什么你的原代码不生效?

_.includes(item, {canHaveCookie: true})会尝试在item的所有属性值里找是否存在完全相等的{canHaveCookie: true}对象,但因为对象是引用类型,即使两个对象结构完全一样,它们的引用地址不同,所以_.includes会返回false,自然筛选不出任何结果。

内容的提问来源于stack exchange,提问作者Acts7Seven

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.26 10:51:41