Displaying both the key and value in a filter list using Angular 1.6's ng-switch

I am currently working on creating a conditional filter for a list of products. Everything was running smoothly until I made changes to the product model to support multiple categories. After this modification, the filter stopped working and an error was displayed: Broken Filter

Here is an example of the JSON structure of the product:

       {
        "title": "Product 2",
        "designer": "Designer 1",
        "id": "314",
        "category": [{
          "name": "Cat 5",
          "name": "Cat 3",

        }],
        "collection": "Collection 2",
        "type": "Type 2",
      },

Below is the controller code for the filter:

myApp.controller('myCtrl', function ($scope, Products) {
$scope.data = Products;
$scope.filter = {};
$scope.categories = ['category','type','collection','designer'];

$scope.addProps = function(obj, array) {
  if (typeof array === 'undefined') {
    return false;
  }
  return array.reduce(function (prev, item) {
    if (typeof item[obj] === 'undefined') {
      return prev;
    }
    return prev + parseFloat(item[obj]);
  }, 0);
}

$scope.getItems = function (obj, array) {
  return (array || []).map(function (w) {
    return w[obj];
  }).filter(function (w, idx, arr) {
    if (typeof w === 'undefined') {
      return false;
    }
    return arr.indexOf(w) === idx;
  });
};
// matching with AND operator
$scope.filterByPropertiesMatchingAND = function (data) {
  var matchesAND = true;
  for (var obj in $scope.filter) {
    if( $scope.filter.hasOwnProperty(obj) ) {
      if (noSubFilter($scope.filter[obj])) continue;
      if (!$scope.filter[obj][data[obj]]) {
        matchesAND = false;
        break;
      }
    }
  }
  return matchesAND;
};
// matching with OR operator
$scope.filterByPropertiesMatchingOR = function (data) {
  var matchesOR = true;
  for (var obj in $scope.filter) {
    if( $scope.filter.hasOwnProperty(obj) ) {
      if (noSubFilter($scope.filter[obj])) continue;
      if (!$scope.filter[obj][data[obj]]) {
        matchesOR = false;
      } else {
       matchesOR = true;
        break;
      }
     }
   }
  return matchesOR;
 };

How can I access only the values for the categories and display unique categories? I have been attempting to get this code to work on jsfiddle for the past 2 hours without success. Here is the link to the fiddle.

EDIT

I have updated the fiddle here: http://jsfiddle.net/48qLjg2z/7/ 1. Lint the json file

Answer №1

There seems to be an issue with your fiddle. Consider starting a new one.

I just made a fresh fiddle and encountered a different error (product not defined).

 var products = product_list

Just a heads up: I utilized Angular 1.5 for this example.

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

Analyzing the elements of an array in JavaScript and making modifications to it based on their values

Looking for a Solution Current Data- id price 1001 200 1001 150 1002 300 1003 50 1002 70 1004 30 Desired Outcome id price 1001 350 1002 370 1003 ...

Obtain cell information when clicking on a specific field within a material-table

import MaterialTable from "material-table"; import ShipmentContext from "../context/ShipmentContext"; const ItemsTable: React.FC = () => { const shipmentcontext = useContext(ShipmentContext); const { filtered } = shipmentcontex ...

Error: Mongoose Schema Undefined when Route is Added in Separate File

For the sake of organizing my code, I made the decision to separate all of my schemas and routes into different files within my directory, and then required them in my app.js. Each schema corresponds with each route. This method has worked for all but one ...

Display personalized content over images utilizing the jQuery galleria plugin

Hey there, I've been successfully using the jquery galleria plugin, but now I'm looking to add some custom content and links that will display in the center of the image. Is it possible to achieve this with galleria? Your insights would be greatl ...

Changing tabs will redirect the url

Having an issue with ASP AjaxControlToolkit tabs. I want the URL to change based on the tab selected by the user. Check out the code snippet below: <asp:TabContainer ID="TabContainer1" runat="server" Width="100%" Height="100%"> <asp:TabPanel ...

How can I extract the width of an uploaded image and verify it using JavaScript?

Is it possible to retrieve the image width through upload using PHP and then validate it in JavaScript? $_FILES['image'] If the image size is not equal to 560px, can we return false and display an alert message using JavaScript? Also, I am won ...

Error: Knockout sortable array failing to render nested elements accurately

As a newcomer to Knockout.js, I have recently delved into the world of JQuery and the knockout-sortable project. My current project involves utilizing a complex data structure to present forms. Specifically, I am attempting to create a nested sortable arra ...

Is it possible to have a div automatically scroll when hovered over, while also hiding the scroll bar specifically for that div?

Is there a way to autoscroll a specific element onmouseover or via an image map while also hiding the scrollbars for that div? I seem to be struggling with this task despite weeks of learning javascript and not being able to find the right solution online. ...

An unrecoverable error has occurred in the SetForm function: PHPMailer::SetForm() method is not defined

While working on form validation in jQuery with a WAMP server, I encountered two errors: Fatal error: Uncaught Error: Call to undefined method PHPMailer:: SetForm() and Error: Call to undefined method PHPMailer::SetForm(). I have already added PHPMailerAu ...

The Tailwind preset is generating CSS code, but the webpage is not displaying the intended styles

Can anyone explain why the preset is generating CSS in the output file, but the styles are not displaying in the browser? When I manually write CSS in newstyle.css, it gets outputted to output.css and renders correctly in the browser. I attempted adding t ...

Steps for resetting the counter to 0 following an Ajax Refresh or Submission to the database

I have been working on a code that successfully sends multiple data to a MySQL Database using JQuery Ajax. Everything works smoothly, but I encountered an issue when trying to refresh the page with ajax and add a new record; it populates the number of time ...

Encountered an error when trying to access the 'modules' property of undefined in the /node_modules/bindings/bindings.js file while working with electron and setting up

1. npm install -g node-gyp 2. npm install serialport -S 3. npm install electron-rebuild -D 4. ./node_modules/.bin/electron-rebuild.cmd and after that, the rebuild process is completed. When I execute the command: npm run electron:serve, I encounter an ...

Updating a connected model in Sequelize using another model

Seeking guidance on updating a model with new associations in Sequelize. The model involves a many-to-many relationship with a join table. Attempted this code snippet: app.patch('/api/team/:id/newplayers', function(request, response){ const pl ...

Uploading an image along with additional information to Strapi using React

Can you assist me with allowing users to post data on Strapi, such as their name, URL, description, and image? I attempted to add an input type file but encountered a 500 error. I suspect this could be due to the need to call localhost:1337/upload, but I& ...

Utilizing a router to control a GET request for accessing an image file

Currently utilizing node.js in conjunction with the express framework, I am attempting to initiate a get request for an image by appending it to the body through $('body').append('<img src="images/image.gif?34567">'). Despite rece ...

Tips for disabling hashbang mode in AngularJs and Node.js

I have been struggling to resolve this issue despite multiple attempts. I am working with angularjs and expressjs. I disabled hashbang mode using $location.html5Mode(true) and included <base href="/">. Initially, it seemed to work fine. However, upon ...

What are the implications of storing data on the browser in the form of a JavaScript array?

Below is the code I have written: var back_arr = [], forward_arr = [], i = 1; $('button').on('click', function(){ var new_value = $('input').val(), old_value = $('.content').html(); i = i + 1; ...

Looking to deactivate the entire keyboard with JavaScript? Make sure that the start key is not disabled, not even Ctrl

Despite my efforts to disable the entire keyboard using JavaScript, I have encountered some limitations. The Windows Start key and Enter key are not being disabled by my script. <script type='text/javascript'> document.onkeydown = functi ...

React-highlightjs failing to highlight syntax code properly

I'm currently using the react-highlight library to highlight code snippets in my next.js application. However, I've encountered an issue with the code highlighting when using the a11y-dark theme. https://i.stack.imgur.com/ip6Ia.png Upon visitin ...

The XHR Get request fails to load the HTML content sent from the Express application

As I embark on building my inaugural express app, I have encountered a shift in sending requests from the front-end. Previously, all requests were initiated by anchor elements for GET requests and form elements for POST requests, with server responses hand ...