Which Is The Best Way To Filter In A Select Input?
I get this response from the API: [ { 'id': 6, 'nombre': 'Pechuga de pollo', 'categoria': 'Pollo', 'existencia': 100 }, { 'id':
Solution 1:
You don't use filter
correctly.
What i suggest is to use an ES6 arrow function :
///This is the function where I apply the filter method:
filtrarProductos () {
this.bebidas = productosLista.filter(x => x.categoria === "Bebida")
}
Solution 2:
Use a computed property. Here's the basic outline of a component that can filter its items
:
<template><ul><liv-for="item in filteredItems":key="item.id">{{ item.text }}</li></ul></template><script>exportdefault {
data() {
return {
// Set this via an API call// Here we assume an item has: id, text, categoryitems: [],
// Use this as the v-model for a select// Here we assume '' is "no selection"category: '',
};
},
computed: {
filteredItems() {
// Show all of the items if there is not category filterif (this.category === '') returnthis.items;
returnthis.items.filter(item => item.category === this.category);
},
},
};
</script>
Solution 3:
I'm little bit confused with the comma which comes after filtradoBebida
.
Seems like it is a property in some object.
Thus this
is needed to call it from inside this object.
Also to be a correct filter predicate it should return a Boolean value.
Yours returns undefined
always.
So, try
filtradoBebida(bebida){
return bebida.categoria == "Bebida"
},
///This is the function where I apply the filter method:filtrarProductos(){
this.bebidas = productosLista.filter(this.filtradoBebida)
}
Solution 4:
You can also use, array.reduce
to create a categoryMap where each category key can hold a list of similar category products. Then use this filtered product list to populate your 3 select components like so:
const productosLista = [{
"id": 6,
"nombre": "Pechuga de pollo",
"categoria": "Pollo",
"existencia": 100
},
{
"id": 7,
"nombre": "Pierna de pavo",
"categoria": "Pollo",
"existencia": 100
},
{
"id": 8,
"nombre": "Lonja de pescado",
"categoria": "Pescado",
"existencia": 200
},
{
"id": 9,
"nombre": "Coca Cola",
"categoria": "Bebida",
"existencia": 200
},
{
"id": 10,
"nombre": "Jugo de naranja",
"categoria": "Bebida",
"existencia": 200
}
]
const categoryMap = productosLista.reduce((acc, dt) => {
acc[dt.categoria] = acc[dt.categoria] ? [...acc[dt.categoria], dt] : [dt]
return acc;
}, {});
console.log(categoryMap);
for (category in categoryMap) {
let sel = document.createElement('select');
let categories = categoryMap[category];
categories.forEach(category => {
let option = document.createElement("option");
option.setAttribute("value", category.nombre);
option.text = category.nombre;
sel.appendChild(option);
});
document.body.append(sel);
}
Post a Comment for "Which Is The Best Way To Filter In A Select Input?"