What is the most effective method for refining options in a select input field?

After receiving a response from the API, the JSON data looks like this:

[
    {
        "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
    }
]

To filter this JSON based on the "categoria" value, I need to populate three different select inputs in my template.

I attempted using the filter() method but it seems my approach is not correct:

///This function specifies the filtering condition:

filtradoBebida(bebida){
             bebida.categoria == "Bebida"
    },

///Here's where I apply the filter method:

filtrarProductos(){
       this.bebidas = productosLista.filter(filtradoBebida)
 }

The goal is to fill one select with items where "categoria" is equal to "Bebida" and another select input with items where the category is "Pollo".

"bebidas" represents an array from my data while ""productosLista" stores the API response as an array.

If you have any alternate methods for populating a select element in Vue.js by filtering values from a JSON data, please share your insights.

Answer №1

Your usage of the filter function is not correct.

I recommend utilizing an ES6 arrow function instead:

// Below is an example of applying the filter method:

filterProducts () {
       this.drinks = productList.filter(item => item.category === "Drink")
 }

Answer №2

I'm finding myself a little unsure about the comma that follows filteredDrink.
It seems like it might be a property within an object.
Therefore, this is necessary to access it from within that object.

Additionally, in order to function as a proper filter predicate, it must return a Boolean value.
The current implementation always returns undefined.

So, consider trying:


filteredDrink(drink){
             return drink.category == "Drink"
    },

///This is the function where I use the filter method:

filterProducts(){
       this.drinks = productList.filter(this.filteredDrink)
 }
 

Answer №3

If you're looking to organize your products into categories and display them in select components, consider using array.reduce. This method can help you create a categoryMap where each category key contains a list of products belonging to that category. You can then use this categorized product list to dynamically populate your select components as shown below:

const productList = [{
    "id": 6,
    "name": "Chicken breast",
    "category": "Chicken",
    "availability": 100
  },
  {
    "id": 7,
    "name": "Turkey leg",
    "category": "Chicken",
    "availability": 100
  },
  {
    "id": 8,
    "name": "Fish fillet",
    "category": "Fish",
    "availability": 200
  },
  {
    "id": 9,
    "name": "Coca Cola",
    "category": "Drink",
    "availability": 200
  },
  {
    "id": 10,
    "name": "Orange juice",
    "category": "Drink",
    "availability": 200
  }
]

const categoryMap = productList.reduce((accumulator, data) => {
  accumulator[data.category] = accumulator[data.category] ? [...accumulator[data.category], data] : [data]
  return accumulator;
}, {});

console.log(categoryMap);

for (category in categoryMap) {
  let select = document.createElement('select');
  let items = categoryMap[category];
  items.forEach(item => {
    let option = document.createElement("option");
    option.setAttribute("value", item.name);
    option.text = item.name;
    select.appendChild(option);
  });
  document.body.append(select);
}

Answer №4

To efficiently filter items, utilize a computed property. Below is a snippet for a component that can handle item filtration:

<template>
  <ul>
    <li v-for="item in filteredItems" :key="item.id">{{ item.text }}</li>
  </ul>
</template>

<script>
export default {
  data() {
    return {
      // Fetch items via an API call
      // Expected properties for each item: id, text, category
      items: [],
      // Bind this to a select element's v-model
      // Default value assumed as ''
      category: '',
    };
  },
  computed: {
    filteredItems() {
      // Display all items if no category filter is selected
      if (this.category === '') return this.items;
      return this.items.filter(item => item.category === this.category);
    },
  },
};
</script>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Using JavaScript, generate ten clickable circles on the screen. Each circle should display the number of times it has been clicked in the center when interacted with

I am currently working on my JavaScript skills and would like to implement a fun project involving 10 colorful circles. While I can easily create these circles using HTML and CSS, I require assistance with the interactive functionality using JavaScript. ...

Extracting data from a webpage's dynamic table using Python with Selenium and

I am planning to extract the data from the JavaScript tables found in the following link: import codecs import lxml.html as lh from lxml import etree import requests from selenium import webdriver import urllib2 from bs4 import BeautifulSoup URL = &apo ...

Struggling to customize Vuetify styles with my own stylesheet

In my current project, I am utilizing Vue2 and Vuetify. One of the main challenges I am facing is that my Vuetify styles are always imported after my own custom styles. I attempted the following: App.vue <template> <v-flex> <v-c ...

Error: Attempting to access 'props' property of undefined when clicking on a button within a React application leads to a TypeError

I'm currently working on implementing two buttons that will enable navigation to different pages within my React app. However, I encountered an error when attempting to use the button labeled "home." TypeError: Cannot read properties of undefined (rea ...

jquery unable to retrieve element

I have implemented a piece of code that adds the 'nav-pills' class to an element with the class 'nav-tabs' when the window width is less than 768px. $(window).on('resize', function () { $('.nav-tabs').toggleClass(&a ...

Communication among kids

My component is quite large, so I will provide a simplified example in the hopes that someone may be able to help me solve my issue. I have an invoice component with child components like 'subtotal', 'vat_subtotal', and 'total&apo ...

FullCalendar fails to load in Bootstrap 4 tab

My current project involves utilizing Bootstrap 4 tabs, and I encountered an issue with displaying a FullCalendar on the second tab. Specifically, I am using version 5.2.0 of the FullCalendar library. While the calendar functions correctly when placed on t ...

What could be the reason for the absence of the loading sign in Chrome, even though it appears when the code is run on Firefox?

I implemented a function to display a loading screen on my HTML page with Google Maps integration. However, when I called the function popUpLoadingScreen() and dismissLoadingScreen() to show and hide the loading message while rendering map markers, the loa ...

The Jquery AJAX function encounters a 403 Forbidden error while making a web service call

I encountered an issue with a web page that includes an AJAX method. Here is the code snippet: $(document).ready(function() { $.ajax({ type: "POST", url: "http://www.webservice.com/blahblah.asmx/blahb123", ...

Executing a JavaScript/jQuery function on the following page

I'm currently working on developing an internal jobs management workflow and I'd like to enhance the user experience by triggering a JavaScript function when redirecting them to a new page after submitting a form. At the moment, I am adding the ...

Tips for transferring date values in an ajax request to a web application handler

I am currently working on plotting a graph between two dates using Google Charts. My goal is to send date values to the controller, which is implemented with webapp2. However, I am facing difficulties in figuring out how to send date values to the controll ...

Utilizing jQuery to seamlessly animate decimal values

Currently facing a challenge while trying to animate a number from 0 to 36.6. The issue is that the end value gets rounded up to 37 instead of displaying as 36.6, which you can observe in this fiddle: http://jsfiddle.net/neal_fletcher/0f3hxej8/ Required ...

Having difficulty implementing a personalized color scheme for the mui component

Attempting to set the background color as midnightBlue but encountering an error: Error: Cannot read properties of undefined (reading '100') Upon reviewing the syntax, no errors were found. Perhaps this issue stems from a dependency problem? ...

A div element with the class name "draggable" is

One of my functions sends notifications to a page by prepending a main div with the notification. Here is the function: function displayNotification(notificationTitle, notificationContent, notificationColor, notificationSize) { console.log('Attem ...

I am currently dedicated to enhancing my background transitions and experimenting with creating smooth fade-ins

I'm almost done with my Weather Forecast page for the FCC challenge. However, I'm not satisfied with how the code for swapping the background works. It just doesn't feel right to me. Unfortunately, I can't figure out how to fix it. Addi ...

Error message for Laravel Passport authentication failure

I've been stuck on this issue for a while now and can't seem to pinpoint the problem. I am using Laravel on the backend and Vue on the front end. Logging in works fine, I receive the token, but when I try to access a route with auth:api, I get an ...

What is the best method for displaying a radio button as selected based on a variable value?

I have a variable that stores the value of a radio button. After checking certain conditions, I want to dynamically select the radio button based on this value. if(cheque_date == system_date) { cheque_value='Current'; } else { cheque_value ...

The database cursor is executing the query, but an OperationalError is being raised due to a missing column in the api_ingredient.meal_id

Seeking assistance in saving data from a menu.json file to my SQL database using Django Rest Framework API. Can someone review my database model for any issues? Additionally, I am encountering an error which I have detailed below. models.py class Meal(mod ...

The 404 error message was encountered when attempting to fetch the Ajax

I am experimenting with using Ajax to load all images from a local folder onto my HTML page. The code I am referring to comes from this question. I am running the files on a (Tomcat 8.5) server in Eclipse and opening the URL in Google Chrome. However, when ...

Exploring the capabilities of xhr2 using pure javascript

Currently, I am attempting to utilize xhr2 in order to read through a json file. Despite my efforts in researching various methods to accomplish this task, none have proved successful thus far. The function featured below my require statements is the one t ...