【发布时间】:2021-12-27 17:55:34
【问题描述】:
我有 json 文件:products.json:
[
{
"id": "1",
"category": "Fruit from USA",
"name": "Banana",
},
{
"id": "2",
"category": "Fruit from Brazil",
"name": "Long Banana",
},
{
"id": "3",
"category": "Vegetable",
"name": "Carrot",
},
{
"id": "4",
"category": "Car from USA",
"name": "Ford",
},
{
"id": "5",
"category": "Car from Germany",
"name": "Audi",
},
{
"id": "6",
"category": "Train from Italy",
"name": "Pendolino",
},
]
然后我有一个数组
testMatch.match: ['Car', 'Fruit'].
我想过滤掉 products.json 以仅返回类别以 ES6 中 matchCategory 的任何元素开头的对象
我目前拥有的是:
const productList = products.filter(filteredCategory => filteredCategory.category.startsWith(testMatch.match));
但如果 testMatch.match 中有超过 1 个元素并且没有元素,则它不起作用 - 它返回所有产品而不是无。
【问题讨论】:
-
您只需要扩展您当前的代码,1. 添加一个检查它是否是一个数组。 2. 遍历 testMatch.match 并查找是否有任何类别以它开头。
标签: javascript arrays