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

如何用Lodash的_.filter筛选属性值含指定内容的对象数组?

用Lodash的_.filter筛选属性值包含指定内容的对象

当然可以,_.filter是Lodash专门用于数组筛选的工具函数,只要给它传入原数组和一个判断回调,就能筛选出符合条件的元素。

原数组定义

const array = [
  {name: "Jim", attributes: "strong, handsome, tall", age: 28},
  {name: "Alice", attributes: "blonde, thin, tall", age: 26},
  {name: "Bob", attributes: "lazy, small, thin", age: 32}
];

筛选attributes包含"tall"的对象

直接用字符串的includes方法判断属性值是否包含目标内容:

const filteredArray = _.filter(array, item => item.attributes.includes("tall"));

执行后得到的结果就是你想要的:

[
  {name: "Jim", attributes: "strong, handsome, tall", age: 28},
  {name: "Alice", attributes: "blonde, thin, tall", age: 26}
]

进阶:更严谨的匹配

如果需要避免误匹配(比如属性里有"taller"也被选中),或者不区分大小写,可以用正则表达式:

// 匹配独立的"tall"词,不区分大小写
const filteredArray = _.filter(array, item => /\btall\b/i.test(item.attributes));

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.14 12:01:02