Filter a nested array in AngularJS and retrieve the parent object as the result

I've recently started experimenting with AngularJS to create checkbox filters for my wine store. Here is an example of an item in my store:

        {
     "id": 17,
     "name": "Ermelinda Freitas Reserva",
     "tag_ids": [40, 12, 56, 6, 60],
     "tag_names": ["Roasted", "Robust", "Blackberry", "Mouth-filling", "Animal"],
     "price": 29,
     "weight": "0",
     "image": "1467208469_wijn1.jpg",
     "stock": 57,
     "year": 1998,
     "special": 0,
     "color_id": 1,
     "color": "Red",
     "region_id": 25,
     "region": "Alentejo",
     "country_id": 6,
     "country": "Portugal",
     "grape_ids": [34, 35, 20],
     "grape_names": ["Castelão", "Touriga Naçional", "Cabernet Sauvignon"]
 }

While I've successfully created filters for countries and other non-array properties, I am now facing a challenge with filtering by grapes. Here's how I started collecting unique grape values:

angular.forEach($scope.wines, function(wine){
  angular.forEach(wine.grape_names, function(grape){
    for(i = 0; i< wine.grape_names.length; i++){
      if($scope.grapes.indexOf(wine.grape_names[i]) === -1) $scope.grapes.push(wine.grape_names[i]);
    };
  });
})

Now, the task is to check if an item has any grapes that match the selected filter. Here is where I need assistance:

$scope.filter.grape = {};
$scope.filterByGrape = function(wine){

  angular.forEach(wine.grape_names, function(grape){

    return $scope.filter.grape[grape] || noFilter($scope.filter.grape);
  })
};

The filters :

<div class="col-lg-3 col-md-4 col-sm-6 " data-id="{{wine.id}}" ng-init="getQuantity(wine.id)" data-ng-repeat="wine in filteredWines =(wines | orderBy:defaultOrder | filter:filterByColor | filter:filterByCountry | filter:filterByGrape | priceRangeFilter:priceRangeSlider | yearRangeFilter:yearRangeSlider | filter:search) | start: (currentPage - 1) * itemsPerPage | limitTo:itemsPerPage">

https://i.sstatic.net/51gQX.png

All feedback and suggestions are appreciated!

Answer №1

Issue lies in the fact that only the initial iteration of the forEach loop is being checked for grape names, causing the function to return prematurely.

$scope.filter.grape = {};
$scope.filterByGrape = function(wine){
  var found = noFilter($scope.filter.grape);
  angular.forEach(wine.grape_names, function(grape){
     found = $scope.filter.grape[grape] || found;
  })
  return found;
};

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

JavaScript only collapsible navigation bar

I have implemented a collapsible navbar using Bootstrap 4 framework according to the documentation provided at this link. The navbar and its contents collapse on small screens, including smartphones, by adding the class .collapse.navbar-collapse. You can ...

javascript monitoring numerous socket channels for echoes

Currently, I am in the process of developing a chat application. On the server side, I am utilizing: php, laravel 5.4, and pusher. On the client side, I have incorporated vue.js along with laravel-echo. Initially, I successfully created a "public chat roo ...

Generate selection choices by looping through a JSON document

I am attempting to develop a search box that will provide autocomplete suggestions based on user input from a key-value pair in a json file. I initially thought using datalist would be the most suitable approach for this task, however, upon running the cod ...

Output the word 'Days', 'Months', or 'Years' depending on the value of N, which represents the number of days

I am currently utilizing moment.js in conjunction with vue 3. I've implemented a function that calculates the disparity between two dates. The functionality works as expected, but here's where my query comes in. The function is structured like so ...

The problem with legends in chart.js not displaying properly

I've been struggling to display the labels "2017" and "2018" as legends on the right side of the chart. I've tried numerous approaches but haven't found a solution yet. The purpose of showing these legends is to easily identify that each co ...

Tips for extracting information from a Javascript Prompt Box and transferring it to a PHP variable for storage in an SQL database

My current issue involves a specific function I want my script to perform: before a user rejects an entry on the server side, the system needs to prompt a text box asking for the reason behind the rejection. The inputted reason should then be saved to a My ...

The error message "Cannot read property 'data' of undefined" is commonly seen in Vue.js when using Axios

I am encountering an issue where the JSON data is not displaying in cards or list format after performing a search. The search functionality appears to be working as I can see the API call with the search text in the console. However, nothing is being disp ...

Displaying properties of objects in javascript

Just starting with JavaScript and struggling to solve this problem. I attempted using map and filter but couldn't quite implement the if condition correctly. How can I find the records in the given array that have a gender of 0 and color is red? let s ...

I am eager to run the code that I retrieved from the server. I have access to the code in my console and I desire for it to execute on the main browser page

Currently, I have a simple Google Chrome Extension that includes a button. By using AJAX, I am fetching a script from a server in my browser's console. Essentially, clicking on the extension reveals a button which, when clicked, fetches the script fro ...

What is the best way to continuously prompt for names from an array until the "stop" command is entered?

I am looking to create a program that continuously prompts the user to input flower names (from a predefined array) until they enter "stop". Additionally, I have a parallel array that stores the prices of each flower. The end goal is to calculate the tot ...

Generate an array using hyperlinks within a list item created by the user

In the process of developing a program, I have included a feature where users can drag and drop .wav files into a playlist-container. These files are then played in the order they are arranged within the playlist-container. Currently, I am working on imple ...

Is $httpBackend failing to mock the request and response?

Attempting to test the $scope.init(id) function involves making a request to the API that returns an array of objects, which needs to be stubbed out with a preset response. Test failure: describe('mysite', function() { var scope, MensDetailCt ...

The internal style and script specified within the <head> section are not being rendered

Within my Joomla website using the T3 template, I inserted the following "Custom Code" just before the closing </head> tag: <style type="text/stylesheet"> div.t3-sidebar.t3-sidebar-right{ background: #F8F8F8 none repeat scroll 0% 0%; ...

Build an array containing the words from the user's input string in reverse order

I'm currently working on a project where users input a string of words (e.g., I love you), and the program should output an array with the words spelled backwards (e.g., I evol ouy). Unfortunately, my code isn't compiling properly even after mult ...

resetting dropdown selections upon page refresh using jQuery and AJAX

Is there a way to reset or clear the values of two select boxes after refreshing the page in CodeIgniter? Currently, both select boxes retain their values after a refresh. Below is the code I am using: <?php echo form_dropdown('cat_id', $ ...

It appears that using "object[prop]" as a name attribute does not function properly in HTML

After using console.log on the req.body I received this output: [Object: null prototype] { 'shoe[name]': 'Shoe Name', 'shoe[description]': '', 'shoe[pictures]': '', 'shoe[collections] ...

What could be causing my jQuery to only toggle the first arrow in my HTML?

I am facing an issue with a series of divs generated from data, each containing an arrow that should toggle an expandable section. Strangely, only the first div is functioning properly: toggling the arrow icon and revealing the content upon click. When th ...

Trouble with disabling default actions and transferring text

When the user clicks on loginAccount, the intention is to extract the text from the element with the id input-1 and assign it to username. This same process should occur for password, followed by form submission. However, despite using e.preventDefault() ...

Separate JavaScript/ASP statements using commas

I'm having trouble comma-delimiting this line in JavaScript, as I keep encountering errors: <a href="javascript:doSubmit(<%= pound & rs("AdvertiserID")%>, <%=rs("AdvertiserName")%>)"> It's Friday, what can I say... The &l ...

Tips for setting a uniform width for all bars in apexcharts bar column width

When working with dynamic data, the length of the data should also be variable. For instance, if the data has a length of 24, the column width should be 35px; similarly, even if the data has a length of 2, the column width should still be 35px. Apexchart ...