After employing a combination of forEach and filter queries in JavaScript to sift through dropdown options, no results are being generated

Hey there fellow developers, I'm currently in the process of developing an app and have reached the stage where I am filtering elements using dropdowns. I am querying a JSON object and comparing it with the selected element in the dropdown at that moment. However, whenever I select an element, no result is shown.

{
   "user":null,
   "products":[
      {
         "product_name":"Chain Saw",
         "product_category":[
            {
               "categories_of_product":"Good"
            },
            {
               "categories_of_product":"Danger"
            },
            {
               "categories_of_product":"Homer"
            }
         ]
      },
      ...
   ]
}

In my methods, I have defined a function that targets a v-modeled global variable which corresponds to a tag in my HTML imported from one of the app components (this part works perfectly). Let's say:


SCRIPT

data(){
 return{
     CategoriesDropDown: "",
 }
},
methods:{
 filterSearch(selectedCategory) {
      this.CategoriesDropDown = selectedCategory;
 },
}

Then, when attempting to filter all my elements based on this.CategoriesDropDown, it doesn't work as expected. Selecting any category from the dropdown causes all products to disappear. Below is the function where I try to access the JSON object and filter based on the selected option in the dropdown:


COMPUTED

callProducts() {
       if (this.CategoriesDropDown) {
        return this.getAllProducts.products.forEach(categories => {
          return categories.product_category.filter(string => {
            return  string.categories_of_product.toUpperCase() === this.CategoriesDropDown.toUpperCase()
            ;
          });
        });
      } else {
        return this.getAllProducts.products;
    }
  }

When nothing is selected: https://i.sstatic.net/Rw7vi.png

When any item is selected: https://i.sstatic.net/2tDeG.png

Any advice on how I can improve this last function to correctly filter my products would be greatly appreciated. Thank you in advance!

Answer №1

Swap out forEach with filter in the code snippet below:

Here's how:

update this.getAllProducts.products.filter(categories => { // only return specific products
  return categories.product_category.filter(string => {
    return string.categories_of_product.toUpperCase() === this.CategoriesDropDown.toUpperCase()
  }).length !== 0 // ensure product belongs to selected category
});

Answer №2

Array.prototype.forEach will always return undefined.

Check out this link for more information on Array.forEach

To prevent getting an undefined response from forEach, it is necessary to reconsider the code structure.

updateProductsList() {
       if (this.selectedCategory) {
        return this.allProducts.filter(category => {
          return category.productCategory.some((cat => {
            return  cat.categoriesOfProduct.toUpperCase() === this.selectedCategory.toUpperCase()
          })
        });
      } else {
        return this.allProducts;
    }
  }

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

Could the Redux store be used to access the state related to specific review comments?

I have a react class component that includes state variables. class NewComponent extends Component { state = { modalIsOpen: false, aa: true, bb: false, cc: false, dd: false, ee: 1, dd: [], cc: [], ff: [], gg: [], ...

Is it possible to create a development build using Npm with React and Typescript?

I have successfully set up a TypeScript React app by using the command below: npx create-react-app my-app --template typescript However, running "npm start" generates development javascript files and launches a development server which is not id ...

Utilizing the `:selected` binding on a dropdown select element that is linked

When working directly with a select tag, I was able to select options based on their values without any issues. Here is an example: <select id="some-select" @input="doSomething($event.target.value)"> <option value="examp ...

Ways to verify if a user is authenticated without relying on request.session

I am currently developing a web application using Express, Docker, and following a Three-layered architecture. In my app, I store user login information in a session and have blogposts as a key resource. To retrieve the blogpostId from the database in the ...

Troubleshooting a JavaScript Script Issue in a NextJs Class

I have been working on my website and decided to incorporate an FAQ page. I used a template for the FAQ section and tried to implement Javascript in my NextJs project, but unfortunately, it's not functioning as expected. var faq = document.getEle ...

Using JavaScript regular expressions to validate currency without relying on jQuery

Looking for a solution to create a money mask for an input field without using jquery in my application. Is it possible to achieve this using regular expressions with 'on key up' events, for example? Below is the code snippet: <tr> & ...

AngularJS button click not redirecting properly with $location.path

When I click a button in my HTML file named `my.html`, I want to redirect the user to `about.html`. However, when I try using `$location.path("\about")` inside the controller, nothing happens and only my current page is displayed without loading `abou ...

able to utilize service within a loop

import { Component, Input, Output, OnInit, OnChanges } from '@angular/core'; import { ViewComponent } from '../view/view.component'; import { HitoService } from '../../services/hito.service'; @Component({ selector: 'ap ...

What about a lightbox with enhanced jQuery features?

As a newcomer to jQuery, I've never experimented with lightboxes before. However, I was tasked with creating something fun for April Fools' Day at work. Naively, I accepted the challenge thinking it would be simple, but now I find myself struggli ...

"Trouble arises with the match() function in relation to email regex validation

After retrieving the HTML content from a website with my function, I am using String.prototype.match along with a regex rule to extract email addresses from that page. However, the issue is that I am receiving a line that matches the regex but does not con ...

Unexpected behavior is being encountered with the else statement, and there are compatibility issues with IE and Mozilla Browser in the overall script

Script is functioning as expected in Google Chrome, but is not responsive in IE and Mozilla browsers JavaScript code: <script src="jquery.min.js"></script> <script> function Run() { if(jQuery('#inputtext').val() == '0 ...

Struggling with debugging an unresponsive outline in Vuetify? Let's figure it out together

Setting up a new Vue3 project with Vuetify3 using Vue CLI. $ vue create playground-vuelidate $ cd playground-vuelidate $ code . $ vue add vuetify $ npm run serve FormInput.vue <template> <v-form> <v-container> <v-row no-gu ...

Modifying the overflow behavior within a Vuetify dialog

Is there a way to have a floating action button positioned on the top right of a dialog, slightly overflowing so it's offset from the dialog itself? I'm struggling to override the 'overflow-y: hidden' property set by v-dialog. <v-dia ...

"What might be causing the error 'cannot access property 'top' of undefined' while trying to read

My website has a sticky navbar fixed at the top, and this is the structure of my sticky navbar: $(function() { $(window).scroll(function() { if ($(window).scrollTop() > $(".b").offset().top + $(".b").height() && $("input").val() == "") { ...

What are the advantages of polymer's inter-component data binding?

I am working on a login component and I want to ensure that the login status is accessible by other components within my application. Is there anyone who can share some functional code snippets or examples? I require a method for binding or event handlin ...

Determining if a variable has been defined in JavaScript

In my JavaScript code, I declare global variables named with the prefix "sld_label" where "label" can be any string. These variables are initialized as objects that contain a function called setval. Now, I have a function that receives a label in a string ...

Javascript code that enables me to specify the type of weather

My intention with this code was to create unique characteristics for different weather types and randomly select one by generating a random number. I defined 11 different weather types as objects of the Weather class. I then implemented a getWeather funct ...

How can I customize the font size of a label within a React Material UI Stepper?

Is it possible to modify the font size of stepper labels in React Material UI? If so, how can I accomplish this? function getSteps() { return [ "OPTION 1", "OPTION 2", "OPTION 3" "OPTION 4& ...

Tips for including descriptions on individual images within the jQuery PhotoStack gallery

Recently, I encountered a challenge. I am currently utilizing a PHP file for accessing images stored in a specific folder. Here is the snippet of my PHP code: <?php $location = 'albums'; $album_name = $_GET['album_name']; $files ...

Unlocking the secrets of integrating Vuex store with JavaScript/TypeScript modules: A comprehensive guide

I am working on a vue application and I have a query. How can I access the store from javascript/typescript modules files using import/export? For example, if I create an auth-module that exports state, actions, mutations: export const auth = { namesp ...