So, I've encountered a challenge that I'd like to address: Filtering an array based on specific conditions using Vue.js and lodash (or raw JavaScript).
The Objects I'm Working With
- I have a list of
Items
. Each item may have (optional)categories
. - The object
Car
can be assigned acategory
.
Array of Objects Items
"data": [
{
"id": 1,
"title": "Item 1",
"categories": [
{
"id": 4,
"title": "category 4",
"description": ""
},
{
"id": 5,
"title": "category 5",
"description": ""
}
]
},
{
"id": 2,
"title": "Item 2",
"categories": []
},
{
"id": 3,
"title": "Item 3",
"categories": []
}
]
Object Car
{
"category": {
"id": 5,
"title": "category 5",
"description": ""
},
"title": "Test"
}
Objective
I aim to display only those Items
that meet at least one of the following criteria:
- The
Item
has at least onecategory
that matches thecategory
of theCar
- The
Item
has no assignedcategory
My Approach
I'm currently using a computed
property to filter this.items
:
computed: {
filteredItems: function () {
let vm = this;
return _.filter(this.items, function (item) {
return _.includes(item.categories, vm.car.category);
});
}
}
Current Outcome:
The filteredItems
array is always empty.