如何在JavaScript中过滤数组中含指定标签'Two'的元素?
问题:筛选包含指定标签的数组元素
现有如下JSON数据结构:
{ "items": [{ "url": "XXX", "title": "XXX", "tags": [ "One", "Two" ] }] }
需求是筛选出items中**tags数组包含"Two"**的元素,现有异步函数代码如下,需要修改filter的回调函数实现需求:
const loadArticles = async () => { fetch(mediumRssFeed, { headers: { Accept: "application/json" } }) .then((res) => res.json()) .then((data) => data.items.filter((item) => ???)) .then((newArticles) => newArticles.slice(0, MAX_ARTICLES)) .then((articles) => setArticles(articles)) .catch((error) => console.log(error)); };
解决方案
将filter的回调函数替换为以下代码即可实现需求:
item => item.tags.includes("Two")
修改后的完整代码段:
const loadArticles = async () => { fetch(mediumRssFeed, { headers: { Accept: "application/json" } }) .then((res) => res.json()) .then((data) => data.items.filter((item) => item.tags.includes("Two"))) .then((newArticles) => newArticles.slice(0, MAX_ARTICLES)) .then((articles) => setArticles(articles)) .catch((error) => console.log(error)); };
补充说明
Array.prototype.includes()会直接判断数组中是否存在目标元素,存在返回true,否则返回false,完全适配filter对回调函数返回布尔值的要求。- 如果需要兼容不支持
includes的老旧浏览器,可以用indexOf()替代:item => item.tags.indexOf("Two") !== -1
内容的提问来源于stack exchange,提问作者Paul VI
相关产品推荐
相关产品推荐

