【发布时间】:2019-11-09 18:28:30
【问题描述】:
我想解决以下问题:我想使用 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至少有一个与Car中的category匹配的category -
Item有没有category设置
我的方法
我正在使用computed 值来过滤this.items:
computed: {
filteredItems: function () {
let vm = this;
return _.filter (this.items, function (item) {
return _.includes (item.categories, vm.car.category );
});
}
},
当前结果:
filteredItems 始终为空。
【问题讨论】:
-
您可以仅使用 ID 进行比较,假设每个类别都是唯一的。您的函数的返回值类似于
return !item.categories.length || _.includes(item.categories.map(category => category.id), vm.car.category.id);
标签: javascript arrays vue.js vuejs2 lodash