[英]How to check if at least one item of an array is included in an array of an object and loop through all objects (JS)
I searched for this and found similar questions but I couldn't figure out a solution for my specific case, so I'm sorry if this is a duplicate.我搜索了这个并发现了类似的问题,但我无法为我的具体案例找到解决方案,所以如果这是重复的,我很抱歉。
I'm trying to build a filter for my website and ran into this problem.我正在尝试为我的网站构建一个过滤器并遇到了这个问题。 I have an array of marker objects and each marker objects has an array of tags (which I named 'types').
我有一个标记对象数组,每个标记对象都有一个标签数组(我将其命名为“类型”)。
When the user selects what types of markers should be displayed, they are added into a 'selectedFilters' array which contains all selected filter types as strings.当用户选择应显示的标记类型时,它们将被添加到“selectedFilters”数组中,该数组包含所有选定的过滤器类型作为字符串。 Now what I want to do is, I want to only display the markers array, filtered by the types that are selected.
现在我想做的是,我只想显示标记数组,按所选类型过滤。 That means if a marker objects contains at least one selected type in its types array it should be displayed.
这意味着如果标记对象在其类型数组中包含至少一种选定类型,则应显示它。
const markers = [
{
type: ['Paper', 'Plastic']
},
{
type: ['Burnable', 'Plastic']
}
{
type: ['NotBurnable']
}
.
.
.
]
const selectedFilters = ['Burnable', 'Plastic']
const filteredMarkers = ????
My idea is to use the filter and some methods to check if at least one filter matches the types array of in each object and return only the objects that pass.我的想法是使用过滤器和一些方法来检查是否至少一个过滤器与每个 object 中的类型数组匹配,并仅返回通过的对象。 I got to the point where I can do that with a hard coded string as filter but not with the actual arrat:
我已经到了可以使用硬编码字符串作为过滤器而不是实际的arrat来做到这一点的地步:
const filteredMarkers = this.markers.filter(
marker => marker.type.some( type => type == 'Plastic')
)
How could I replace the hard coded string with the actual array and loop through it?如何用实际数组替换硬编码字符串并循环遍历它? Appreciate any advice, tips and suggestions.
感谢任何建议、提示和建议。 Btw it's a vue project.
顺便说一句,这是一个 vue 项目。 Maybe there is a different way to build filters in vue?
也许在 vue 中构建过滤器有不同的方法?
You are very close in your attempt.你的尝试非常接近。 You just need to check if
selectedFilters
.includes()
one of the marker types.您只需要检查
selectedFilters
.includes()
是否是其中一种标记类型。
const markers = [ { type: ['Paper', 'Plastic'] }, { type: ['Burnable', 'Plastic'] }, { type: ['NotBurnable'] } ] const selectedFilters = ['Burnable', 'Plastic'] const filteredMarkers = markers.filter( marker => marker.type.some(type => selectedFilters.includes(type)) ) console.log(filteredMarkers)
const markers = [
{
type: ['Paper', 'Plastic']
},
{
type: ['Burnable', 'Plastic']
},
{
type: ['NotBurnable']
}
]
const selectedFilters = ['Burnable', 'Plastic']
const filteredMarkers = markers.filter(function(marker, index, arr) {
return marker.type.some(type => selectedFilters.includes(type));
});
console.log(filteredMarkers);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.