JavaScript如何按多条件过滤对象数组提取符合要求的元素
需求说明
现有如下结构的JavaScript对象数组:
const fruits = [{ "id": "1", "title": "Banana", "description": "1 Minute" }, { "id": "2", "title": "Apple", "description": "2 - 3 Days" }, { "id": "3", "title": "Manggo", "description": "10 - 20 Days" }, { "id": "4", "title": "Orange", "description": "10 - 20 Days" }, { "id": "5", "title": "Grape blue", "description": "10 - 20 Days" }, { "id": "6", "title": "Grape red", "description": "10 - 20 Days" }]
需要过滤出同时满足以下两个条件的对象:
- description字段值为*"10 - 20 Days"*
- title字段不包含字符串*"Grape"*
期望得到的结果如下:
[ { "id": "3", "title": "Manggo", "description": "10 - 20 Days" }, { "id": "4", "title": "Orange", "description": "10 - 20 Days" } ]
实现代码
直接使用JavaScript数组原生的filter方法即可实现:
const result = fruits.filter(item => item.description === "10 - 20 Days" && !item.title.includes("Grape") )
代码说明
filter方法会遍历数组的每一项,将符合判断条件的项保留下来,最终返回新的结果数组,不会修改原数组- 第一个判断条件
item.description === "10 - 20 Days"严格匹配description字段的要求值 - 第二个判断条件
!item.title.includes("Grape")中,includes方法用于检测字符串是否包含指定子串,前面的!做取反操作,即只保留标题不包含"Grape"的项
内容的提问来源于stack exchange,提问作者Rama
相关产品推荐
相关产品推荐

