Organizing elements in a javascript array by their attributes using AngularJS

Picture this scenario: a collection of different wines:

[  
   {  
      "name":"wine A",
      "category":[  
         "red",
         "merlot"
      ]
   },
   {  
      "name":"wine B",
      "category":[  
         "white",
         "chardonnay"
      ]
   },
   {  
      "name":"wine C",
      "category":[  
         "white",
         "chardonnay",
         "red",
         "merlot"
      ]
   }
]

I am tasked with creating a filtering/grouping feature using AngularJS. For example, if a user selects "chardonnay", the filtered results should display:

Results: wine B, wine C

Although I have a functioning example, there is a need to review the data structure of that example. It does not define arrays within the object items. What adjustments should be made in the controller to align it with the above (array) structure?

var app = angular.module("myApp", []); 
app.controller("myCtrl", function($scope) {
  $scope.wines = [
    {
      name: "Wine A",
      category: "red"
    },
    ...
   
});

app.filter("capitalizeFirst", function() {
  return function(str) {
    str = str || "";
    return str.substring(0, 1).toUpperCase() + str.substring(1).toLowerCase();
  };
});
<script src... angular.min.js"></script>
<div ng-app="myApp">
  <div ng-controller="myCtrl">
    <div ng-repeat="(prop, ignoredValue) in wines[0]" ng-init="filter[prop]={}">
      <b>{{prop | capitalizeFirst}}:</b>
      ...
      
</div>

Answer №1

To filter, simply utilize the search filter :

<b>Select a category: (Hard coded)</b>
            <ul>
              <li style="cursor:pointer" ng-click="click_filter('red')">red</li>
              <li style="cursor:pointer" ng-click="click_filter('merlot')">merlot</li>
              <li style="cursor:pointer" ng-click="click_filter('white')">white</li>
              <li style="cursor:pointer" ng-click="click_filter('chardonnay')">chardonnay</li>
            </ul>

    <b>Result</b>
          <div ng-repeat="wine in wines | filter:search ">
          <b>{{wine.name}}</b> - (category): {{wine.category}}
          </div>
    </div>

JS:

 $scope.click_filter = function(item) {
         $scope.search = item;
     }

For dynamic categories, you can explore eliminating duplicate entries from ng-repeat (as shown in my Plunker example).

View Plunker:

Answer №2

When transitioning from a list to an array, adjustments need to be made in how options are retrieved and a call to flat() needs to be added

  $scope.getOptionsFor = function(propName) {
    return ($scope.wines || [])
      .map(function(w) {
        return w[propName];
      })
      .flat()
      .filter(function(w, idx, arr) {
        return arr.indexOf(w) === idx;
      });
  };

Subsequently, the filterByProperty function must be capable of handling arrays as well as individual values:

  $scope.filterByProperties = function(wine) {
    // Use this code snippet for AND matching
    var matchesAND = true;
    for (var prop in $scope.filter) {
      if (noSubFilter($scope.filter[prop])) 
        continue;

      if(Array.isArray(wine[prop])) {
          let matchCount = 0;  
          for(let i in wine[prop]) {
            if ($scope.filter[prop][wine[prop][i]]) {
              ++matchCount;
            }
          }
          let trueFilter = 0
          Object.values($scope.filter[prop]).forEach(element => {
              if (element)
                ++trueFilter
          });
          matchesAND = matchCount == trueFilter;
          if (! matchesAND)
            break
      }
      else {
      if (!$scope.filter[prop][wine[prop]]) {
        matchesAND = false;
        break;
      }}
    }
    return matchesAND;
  };

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

Identifying the HTML Hidden Attribute Using JavaScript Without Dependencies

As someone working in the analytics field, I often rely on CSS selectors to address various issues. Currently, I am faced with a task on a website where I need to determine whether a <p> element is hidden or visible. There are two possible scenarios: ...

What could be causing the remove attribute API to not function properly only for the "is" attribute?

var divElement = document.createElement("div"); var innerHTMLText = "<div id='issue' is='if'> some content </div>"; divElement.innerHTML = innerHTMLText; document.body.appendChild(divElement); var newDivElement = document.qu ...

Cause: Trying to serialize an `object` that is not JSON serializable (such as a "[object Date]"). Ensure that only JSON serializable data types are returned

Currently, I am utilizing Prisma along with Next.js. My issue arises when attempting to retrieve content from Prisma within the getStaticProps function; while it successfully fetches the data, I encounter difficulties passing it on to the main component. e ...

Refreshing the page causes JavaScript to fail loading

Recently, I encountered a puzzling error. Upon visiting this link The carousel fails to load properly near the bottom of the page. However, if you click on the logo or navigate back to the home page, it works fine. Additionally, performing a command + r ...

How to enhance a jQuery tab control by implementing custom JavaScript forward and back arrows?

Although there are other questions related to this topic, mine is unique. I have a scrolling jQuery feature that utilizes tabs for selection and is automated. Modifying the layout is challenging because it is dynamic and depends on the number of items in t ...

Shifting Angular Component Declarations to a New Location

Here's a question that might sound silly: In my Angular project, I am looking to reorganize my component declarations by moving them from angular.module.ts to modules/modules.modules.ts. The goal is to structure my src/app directory as follows: src ...

How can I use JavaScript or CSS to identify the specific line on which certain words appear in the client's browser?

Imagine I have the following HTML structure: <div> <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco labor ...

I Am unable to locate the '...' after applying the text-ellipsis style to a div

https://i.stack.imgur.com/Tsmf5.png The ellipsis '...' is not showing up even after I have applied text-ellipsis, overflow hidden, and nowrap to this div. Take a look at my code: import Image from "next/future/image"; import Link from ...

A Simple Guide to Setting a Background Image in React Native with the Nativebase.io Library

What is the process for including a background image in React Native with the help of the Nativebase.io Library? I have a specific screen where I need to incorporate a background image, with all other elements positioned at the center of the image. ...

The Stripe payment form effortlessly updates in real-time thanks to the powerful @stripe/react-stripejs module

I am experiencing some difficulties with implementing Stripe payment in my Medusa-JS Next JS frontend. Whenever I enter card details in the checkoutForm, the entire StripePayment component keeps re-rendering every time I click on anything within the form ...

Connects URLs to the displayed outcomes in jQuery Auto-suggest Interface

This particular code snippet has been modified from a tutorial on jQuery autocomplete <!doctype html> <html lang="en> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> ...

What is the best method for returning the AJAX outcome to the JSP page?

Using AJAX, I am able to post data from my JSP page to my servlet. $.ajax({ url: 'myServlet?action=FEP', type: 'post', data: {machine: i, name: txt}, // where i and txt hold certain values success: f ...

React compatibility problem with Internet Explorer 11

I'm encountering a problem with an error message stating "Expected identifier" in this code snippet. Any thoughts on what might be causing this issue? It seems like the problematic section of the code is originating from the transpiled version of th ...

Payload bytes do not match the expected byte values

I am facing an issue where the image data sent by the user is getting saved on the server in a corrupt state. Here is the structure of my setup: - api . index.js - methods . users.js (I have omitted unrelated files) There is a server.js outside ...

Performing a search within a JSON data column in MySQL

I'm currently facing a challenge with my MySQL database column that stores JSON array encoded strings. My goal is to search within the JSON array for values where the "Elapsed" is greater than a specific number and then retrieve the corresponding Task ...

The updates made to a form selection using Ajax do not reflect in jQuery's .serialize or .val functions

When using the .load jQuery function to retrieve a form and place it in the document body, I encounter an issue. After loading the form, I manually change the select value and attempt to save the form using an ajax .post request. However, when trying to ...

Unable to extract an NSString from a JSON entity

When I retrieve an element from an NSMutableDictionary that was created by deserializing data using NSJSONSerialization after an NSURLSessionDataTask, I encounter an issue. Here's how it looks: NSDictionary* json = [NSJSONSerialization JSONObjectWith ...

How to include a key-value pair to a JSON object within an array using JavaScript

I am looking to include the following functionality in the JSON data provided below: "Check if the key name default exists, and if it does, add another key within the same object => ("pin" : 91)." I have attempted to achieve this using the code snippet b ...

ModSecurity Action Causing AJAX Problem

An error is being triggered by the URL below with a message of "Modsecurity forbidden status code: 403". This URL is being returned from an AJAX call. like ? and active = ?&params='%ABCDE%'|1&element_id=hello If I remove %% from ABCDE ...

Utilizing Twitter API authentication to prevent hitting rate limits

Currently, I am implementing the Twitter API to showcase the most recent tweets from 4 distinct users on my webpage. It seems that once a certain number of calls are made, an error message appears stating "NetworkError: 400 Bad Request" and prevents the tw ...