我正在尝试过滤一个对象数组,其中对象中的某个键包含一个字符串数组。这是数据结构的示例。
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
。那里不需要支架访问。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句