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

Filter an array using conditions stored in another array

I have this array of objects:

const parks = [
    {
        "properties": {
            "name": "Park 1",
            "parking": "",
            "type": "park",
            "picnic_area": 1
        },
    },
    {
        "properties": {
            "name": "Park 2",
            "parking": 1,
            "type": "park",
            "picnic_area": ""
        },
    }
];

The page have a list of checkboxes. When user check/uncheck one of then, a function generate an object with all the selected checkboxes:

{
    "parking": true,
    "picnic_area": true
}

My question is: how can I use this object to generate the conditions inside a filter() function? Something like:

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 parksData = parks.filter(object => {
    return object_condition_1 && object_condition_2;
});

>Solution :

For starters, you need to rename keys in the filters object so that they match properties’ keys, that is, parking, not parkings. Then,

result = parks.filter(p =>
    Object.keys(filters).every(key => 
        Boolean(p.properties[key]) === Boolean(filters[key]))
)

This implements an AND condition, that is, only return objects that match all filters. If you need OR instead, replace every with some.

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