我想解决以下问题:我想使用Vue.js和lodash(或纯JavaScript)按特定条件过滤数组。
Items
的列表。每个项目都包含(可选)categories
。 Car
可以具有category
。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": []
}
]
Car
{
"category": {
"id": 5,
"title": "category 5",
"description": ""
},
"title": "Test"
}
我只想显示至少通过以下规则之一的Items
:
Item
至少有一个category
与category
的{{1}}匹配Car
设置了否 Item
我正在使用category
值来过滤computed
:
this.items
computed: {
filteredItems: function () {
let vm = this;
return _.filter (this.items, function (item) {
return _.includes (item.categories, vm.car.category );
});
}
},
始终为空。
答案 0 :(得分:3)
您需要对categories
进行另一级检查,因为您需要针对其中的每个项目进行测试。使用常规javascript,您可以使用some()
进行操作,如果有任何一项匹配,则返回true。
let 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": []}]
let car = {"category": {"id": 5,"title": "category 5","description": ""},"title": "Test"}
let filtered = data.filter(item => !item.categories || item.categories.length === 0 || item.categories.some(cat=> cat.id === car.category.id))
console.log(filtered)
答案 1 :(得分:1)
使用lodash
,您需要类似的东西
result = _.filter(data, ({categories}) =>
_.isEmpty(categories) ||
_.some(categories, cat => cat.id === car.category.id))
如果您想比较整个类别对象,而不仅仅是ID,那么
_.filter(data, ({categories}) =>
_.isEmpty(categories) ||
_.some(categories, cat => _.isEqual(cat, car.category)
))