首页 > 解决方案 > 如何过滤出一个字符串数组?

问题描述

我正在尝试过滤一个对象数组,其中对象中的某个键包含一个字符串数组。这是数据结构的示例。

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"))

这将返回第一个条目,因为整个字符串都匹配。我想要的是在部分字符串而不是整个字符串之间进行比较,但我似乎无法得到任何工作。有谁知道如何比较字符串数组以使第一个示例返回第二个条目?

标签: javascriptarraysobjectfiltersubstring

解决方案


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. 那里不需要括号访问。


推荐阅读