如何过滤掉字符串数组?

How to filter out an array of strings?

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

let array = [{
  tags: ["this is a tag"]
}, 
{
  tags: ["this is not a tag"]
}]

我需要根据特定条件过滤此数组。这是我开始的内容。

const filtered = array.filter(entry => entry["tags"].includes("n"))

这 return 除了以下内容之外什么都没有。

const filtered = array.filter(entry => entry["tags"].includes("this is a tag"))

这 return 是第一个条目,因为整个字符串都匹配。我想要的是比较部分字符串而不是整个字符串,但我似乎什么都做不了。有谁知道如何比较字符串数组,以便第一个示例 return 第二个条目?

您的 includes 正在检查数组 ["this is a tag"] 是否包含字符串 "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 的。那里不需要括号访问。

使用正则表达式中的字符串并将其与 tags 数组匹配。

let array=[{tags:["this is a tag"]},{tags:["this is not a tag"]}];

function check(arr, str) {
  const regex = new RegExp(`${str}`);
  return arr.filter(({ tags }) => {
    return tags[0].match(regex);
  });
}

console.log(check(array, 'this'));
console.log(check(array, 'n'));
console.log(check(array, 'targ'));