我有 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 個元素并且沒有元素,則它不起作用 - 它回傳所有產品而不是無。
uj5u.com熱心網友回復:
您也可以match使用Array#somefind進行迭代并退出。
const
products = [{ 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" }],
match = ['Car', 'Fruit'],
productList = products.filter(({ category }) =>
match.some(m => category.startsWith(m))
);
console.log(productList);
.as-console-wrapper { max-height: 100% !important; top: 0; }
uj5u.com熱心網友回復:
使用Array.some()它是否與任何在字串的開始測驗testMatch.match。
const products = [{
"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",
},
];
const testMatch = {
match: ['Car', 'Fruit']
};
const productList = products.filter(filteredCategory =>
testMatch.match.some(match => filteredCategory.category.startsWith(match)));
console.log(productList);
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/394854.html
標籤:javascript 数组
