javascript - 如何过滤出一个字符串数组?
问题描述
我正在尝试过滤一个对象数组,其中对象中的某个键包含一个字符串数组。这是数据结构的示例。
let array = [{
tags: ["this is a tag"]
},
{
tags: ["this is not a tag"]
}]
我需要根据某些标准过滤这个数组。这是我开始的。
const filtered = array.filter(entry => entry["tags"].includes("n"))
这不会返回任何内容,但会返回以下内容。
const filtered = array.filter(entry => entry["tags"].includes("this is a tag"))
这将返回第一个条目,因为整个字符串都匹配。我想要的是在部分字符串而不是整个字符串之间进行比较,但我似乎无法得到任何工作。有谁知道如何比较字符串数组以使第一个示例返回第二个条目?
解决方案
您includes
正在检查数组是否["this is a tag"]
包含 string "n"
,它显然不包含。
如果您要检查数组是否包含包含特定字母的字符串,则需要进行更深入的搜索:
let array = [{
tags: ["this is a tag"]
}, {
tags: ["this is not a tag"]
}];
const filtered = array.filter(entry => entry.tags.some(tag => tag.includes("n")))
console.log(filtered);
还要注意我是如何entry["tags"]
用entry.tags
. 那里不需要括号访问。
推荐阅读
- git - SSH 无法正常工作,导致 ssh 错误致命:协议错误:错误的行长度字符:git@
- authorization - 为什么 Envoy ext-authz 不遵守 connect_timeout?
- javascript - Jest spyOn 使函数“未定义”
- javascript - 表单提交后如何在html中使文本字段不可编辑
- java - Box2D通过加速、匀速移动和最后减速移动到目的地
- android - 如何对像whatsapp这样的android通知进行分组?因为 setGroup 不适合我
- java - SOAP Post 适用于 Postman,但不适用于 Java
- c# - 从 .net core web api 中的 Helper 类访问 HttpContextAccessor
- github - 致命:不支持协议“git@https”
- excel - 无法从包含数据的工作表中查找最后一列