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;
});
CodePudding user response:
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
.
CodePudding user response:
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)));