0

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 simply need to extend your current code, 1. add a check it's an array or not. 2. loop over testMatch.match and find if any of category starts with it. – Code Maniac Dec 27 '21 at 18:01

2 Answers2

5

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; }
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392
3

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);
Barmar
  • 741,623
  • 53
  • 500
  • 612