I would like to filter out each in an array if the value of category is of a user selected value.
For example, I have an array of exampleData
[
{
"node": {
"id": "377856cd-9477-58a4-9596-888ebc8c03d5",
"title": "Tubing & Sledding",
"category": [
"Winter"
]
}
},
{
"node": {
"id": "a7370249-af7a-538a-aaae-91f308575bb8",
"title": "Snowmobiling",
"category": [
"Summer",
"Winter"
]
}
},
{
"node": {
"id": "4136389a-77b7-5e07-8c95-1c856983d27b",
"title": "Snowshoeing",
"category": [
"Winter"
]
}
},
{
"node": {
"id": "79fc5efa-e1a4-5e65-94cd-97a5245ed0af",
"title": "X-Country Skiing",
"category": [
"Winter"
]
}
}
]
And I would like to filter the array to only return the objects with Summer included in the category field array .
To do this, I have tried
const exampleCategory = exampleData.filter(({ node: category }) => {
activity.category.includes('Summer');
});
Yet, console.log(exampleCategory) shows with zero results.
What have I done wrong here?
You should return the boolean result of calling .includes:
const exampleCategory = exampleData.filter(({ node: { category }}) => {
return category.includes('Summer');
});
Also, you can directly do that without return
const exampleCategory = exampleData.filter(({ node: { category }}) => category.includes('Summer'));
Example
const exampleData = [{ "node": { "id": "377856cd-9477-58a4-9596-888ebc8c03d5", "title": "Tubing & Sledding", "category": [ "Winter" ] } }, { "node": { "id": "a7370249-af7a-538a-aaae-91f308575bb8", "title": "Snowmobiling", "category": [ "Summer", "Winter" ] } }, { "node": { "id": "4136389a-77b7-5e07-8c95-1c856983d27b", "title": "Snowshoeing", "category": [ "Winter" ] } }, { "node": { "id": "79fc5efa-e1a4-5e65-94cd-97a5245ed0af", "title": "X-Country Skiing", "category": [ "Winter" ] } }];
const exampleCategory = exampleData.filter(({ node: { category }}) => category.includes('Summer'));
console.log(exampleCategory);
.as-console-wrapper { max-height: 100% !important; top: 0; }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With