Tengo un archivo json: productos.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", }, ]Entonces tengo una matriz
testMatch.match: ['Car', 'Fruit'].Quiero filtrar products.json para devolver solo los objetos que tienen una categoría que comienza con cualquiera de los elementos de matchCategory en ES6
Lo que tengo hasta ahora es:
const productList = products.filter(filteredCategory => filteredCategory.category.startsWith(testMatch.match));Pero no funciona si hay más de 1 elemento en testMatch.match y si no hay ninguno, devuelve todos los productos y no ninguno.
También puede iterar la match con Array#some y salir al buscar.
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; }Usa Array.some() para probar si comienza con alguna de las cadenas en 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);