Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How do I filter objects based on keys which have value as an array in React?

Here is an example of the dataset:

[
    {
        "crystal_name": "African Tourmaline",
        "properties": ["Grounding", "Protection"]
    },
    {
        "crystal_name": "Amazonite",
        "properties": ["Calming", "Balance", "Truth"]
    },
    ....
]

I’m trying to figure out how to filter the items when the user selects one or more properties..
For example if the user selects "Grounding".. then all the items with "grounding" should appear and if the user selects "calming" and "balance" then only the items with those properties should appear.

I’m new to React.. So I tried the following code:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

const filterItems = () => {
  if(selectedFilters.length > 0) {
    let tempItems = selectedFilters.map((selectedCategory) => {
        let temp = crystals.filter((crystal) => {
        let flag = 0;
        for(let i=0; i<crystal.properties.length; i++) {
            if(crystal.properties[i] === selectedCategory) {
                flag = 1;
                break;
            }
        }
        if(flag === 1) return crystal;
        });
        return temp;
    })
    console.log(crystalsToShow);
    console.log(tempItems);
    setCrystalsToShow(tempItems.flat());
  } else {
    setCrystalsToShow([...crystals]);
  }
};

But according to this logic it will show the items even if one of them will be present in the set of values in array.

>Solution :

Here’s a revised version of your filterItems function that filters the crystals based on all selected categories:

const filterItems = () => {
  if (selectedFilters.length > 0) {
    const filteredCrystals = crystals.filter((crystal) => {
      return selectedFilters.every((selectedCategory) => {
        return crystal.properties.includes(selectedCategory);
      });
    });
    setCrystalsToShow(filteredCrystals);
  } else {
    setCrystalsToShow([...crystals]);
  }
};
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading