如何用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
相关产品推荐
相关产品推荐

