简体   繁体   English

JavaScript Array.includes - 如何使用扩展运算符检查多个值

[英]JavaScript Array.includes - how to check multiple values with spread operator

I am working on a Vuejs project where I have an array of posts.我正在开发一个 Vuejs 项目,其中有很多帖子。 I have a menu where I can select one or more categories which updates the array of posts to only display the posts with the categories selected.我有一个菜单,我可以在其中 select 一个或多个类别更新帖子数组以仅显示所选类别的帖子。 Due to the project code having to be protected, I created a dummy example.由于必须保护项目代码,我创建了一个虚拟示例。

 const arr = [ { id: 1, categories: ["animals"] }, { id: 2, categories: ["cities"] }, { id: 3, categories: ["house"] }, { id: 4, categories: ["house", "cities"] }, { id: 5, categories: ["new"] } ]; const selectedItems = ["house", "new"]; const filteredArr = arr.filter((a) => a.categories.includes(...selectedItems)); console.log("result", filteredArr); // "result", [ { id:3, categories: ["house"] }, { id: 4, categories: ["house", "cities"]} ]

The issue that I am currently running into is that when I spread the variable selectedItems into the.includes() array method, it only targets the first item in that array which is "house".我目前遇到的问题是,当我将变量selectedItems传播到 .includes() 数组方法中时,它只针对该数组中的第一项,即“house”。 As a result I only return the posts with the id 3 & 4 while not returning id 5 which has the "new" category tied to it.因此,我只返回 id 为 3 和 4 的帖子,而不返回与“新”类别相关的 id 5。

How would I be able to return all the posts based on the categories that I have selected?我如何能够根据我选择的类别返回所有帖子? Is.includes() even the correct array method? Is.includes() 甚至是正确的数组方法吗?

includes is fine, but you can't use it on its own - try linking it with some to make sure at least one of the selectedItems is include d includes很好,但您不能单独使用它 - 尝试将它与一些链接以确保至少有一个selectedItems include d

 const arr = [ { id: 1, categories: ["animals"] }, { id: 2, categories: ["cities"] }, { id: 3, categories: ["house"] }, { id: 4, categories: ["house", "cities"] }, { id: 5, categories: ["new"] } ]; const selectedItems = ["house", "new"]; const filteredArr = arr.filter((a) => selectedItems.some(item => a.categories.includes(item))); console.log("result", filteredArr);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM