简体   繁体   中英

Filter json based on key and match it against one of the values from array

I have json file: 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",
},
]

Then I have an array

testMatch.match: ['Car', 'Fruit'].

I want to filter out products.json to return only objects that have category starts with any of elements of matchCategory in ES6

What i have so far is:

const productList = products.filter(filteredCategory => filteredCategory.category.startsWith(testMatch.match));

But it does not work if there is more than 1 element in testMatch.match and if there is none - it returns all products and not none.

You could iterate match as well with Array#some and exit on find.

 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; }

Use Array.some() to test if it starts with any of the strings in 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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM