0

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:

const parksData = parks.filter(object => {
    return object_condition_1 && object_condition_2;
});
1
  • Can you have false values in the filter object, like parkings: false? Or other values that need to be matched explicitly? Commented Oct 17, 2022 at 19:48

2 Answers 2

3

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.

Sign up to request clarification or add additional context in comments.

Comments

0

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

const filter = {
    "parkings": false,
    "picnic_areas": true
};

console.log(parks.filter(park => (filter.parkings && !!park.properties.parking) || (filter.picnic_areas && !!park.properties.picnic_area)));

1 Comment

Thanks. The problem is: I need a more dynamic approach because the real scenario can have multiples checkboxes/conditions.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.