简体   繁体   中英

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. 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. I got to the point where I can do that with a hard coded string as filter but not with the actual 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. Maybe there is a different way to build filters in vue?

You are very close in your attempt. You just need to check if selectedFilters .includes() one of the marker types.

 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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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