output an array based on a specified key/value relationship

Looking to filter results based on a key/value pair in an array?

Consider this example array:

.factory('dishesFactory', function (){
var factory = {
    dishes :[
 {nameEnglish: 'TAPENADE',
  nameLocal: 'Tapenade',
  description: 'xxxxxx ',
  region: 'Provence-Alpes-Côte d\'Azur',
  regioncode: 'FR.B8',
  itemid: 'FR002',
  cuisineTypeIsoCode: 'FR',
  dishCategory: 'Entrée / Appetizers',
  country: 'France',
  type: 'top_10'},

 {nameEnglish: 'GREEK STYLE MUSHROOMS  ',
  nameLocal: 'Champignons à la grecque',
  description: 'xxxxxxx',
   region: 'All',
  regioncode: '',
  itemid: 'FR008',
  cuisineTypeIsoCode: 'FR',
  dishCategory: 'Entrée / Appetizers',
 country: 'France',
  type: ''}

 // more entries 

 ];

If you want to modify the JavaScript code so it only returns items with type: 'top_10', take a look at this snippet below:

.filter('selectedDishType', function() {
return function(dishes, dishTypes) {
console.log(dishTypes);
if (dishTypes.length > 0) {
    return dishes.filter(function(dish) {
        return dishTypes.indexOf(dish.dishCategory.toLowerCase()) != -1;
    });
} else {

    return dishes.filter(function(dish){ 
        return dish.type === 'top_10';
    });
  }
 };
})

Struggling with syntax changes? Check out the updated solution provided below for reference:

.filter('selectedDishType', function() {
return function(dishes, dishTypes) {
console.log(dishTypes);
if (dishTypes.length > 0) {
    return dishes.filter(function(dish) {
        return dishTypes.indexOf(dish.dishCategory.toLowerCase()) != -1;
    });
} else {

    return dishes.filter(function(dish){
        return dish.type === 'top_10';
    });
  }
};
})

Answer №1

Revise your filter function like this

update filters (dish) {
  isDishExist = dish.category.toLowerCase().indexOf(dishTypes) !== -1;
}

This updated code should do the trick!

Answer №2

If you're looking to filter through a list using underscore, here's an example of how you can do it:

var topRatedItems = _.filter(items, function(item){ return item.rating >= 9; });

For even more flexibility, check out the .where method in underscore here.

"where_.where(list, properties) This method searches through each value in a list and returns items that match all specified key-value pairs. "

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

Utilize Server Side Includes in your JavaScript code

When the query string is parsed, a specific section of code SSI is included in the footer page. Here are some examples of query strings: ?headId=520&genderType=2 ?headId=600&genderType=1 function GetQueryStringParams(sParam){ var sPageURL ...

Is there a way to import a module generated by typescript using its name directly in JavaScript?

I am trying to bring a function from a typescript-generated module into the global namespace of JavaScript. The typescript module I have is called foo.ts: export const fooFn = (): string => { return "hello"; }; Below is the structure of my HTML file ...

What other local variables can be passed into a controller in addition to the $scope variable?

Angular allows for dependencies to be injected, but it's important to note that injecting $scope into a directive doesn't work. Is there a definitive list available outlining what can be injected into controllers and what cannot? What about direc ...

Display thumbnail images in jquery-ui dropdown menu

Hello, I'm looking to display a small image (the user's thumbnail) on the jquery-ui dropdown by making an ajax call. As someone new to ajax and unfamiliar with jquery-ui, I would appreciate some guidance in the right direction. Thank you! HTML/J ...

There is a missing dependency in the root installation of a custom node module

Currently, I have a project for an app and two separate node module projects. The dependency structure looks something like this: App { NodeModule1 { NodeModule2, ... }, ... } The issue I am facing is that instead of NodeModule2 being instal ...

Any suggestions on how to incorporate the variable into the inline JavaScript [[]] API path?

I have a query regarding creating a URL in JavaScript, but I'm unsure how to include variables within th:inline="javascript". Below is my code snippet: <script th:inline="javascript"> $(function() { $('#querySubmit').click(queryS ...

Transforming the jQuery tooltip to be shown in a column layout

Hello, I am currently using the displayTag library to showcase some tables. My goal is to include a tooltip on each display:column element by utilizing jQuery. Below is the code snippet in question: <c:set var="titleName"><wp:i18n key="FILENAME" ...

Unable to adjust the x-axis time display in Chart.js

Within my ChartData Component, I am fetching data from an API and displaying it through a chart. The crucial aspect here is the determine Format Logic, which determines the time format of the data. My main challenge lies in changing the time display when s ...

Avoid the rendering of child elements in React

How can I skip rendering children in React? I want to enclose existing DOM nodes on a page within a React component. I need to render the frame only, excluding the static content which already exists as pre-existing DOM nodes. Is there a way to achieve t ...

Guide to integrating jssor into an AngularJS application

Struggling to integrate jssor with angularjs, it seems to be failing because jssor is being initialized before angularjs, causing the ng-repeat elements to not resolve correctly. <div id="slider1_container"> <div u="slides"> <!-- Th ...

Eliminate the border and style of a link that was clicked before in a React/Next.js

I've created a function where clicking on an element adds borders using onClick trigger. Here's the code snippet from the component: import { useEffect, useState } from 'react'; import Link from 'next/link'; import Logo from ...

Adjust the Scope in Angular-Charts.js Post-Rendering

I am currently facing a challenge with displaying multiple charts using the angular-charts.js framework. The issue is that I require all the charts to have the same scale, but each chart currently has its own scale based on the displayed data. Unfortunatel ...

Is there a way for me to convert this JSON object back into a string?

Presently, I possess this specific JSON object "name": "Luke Skywalker", "height": "172", "mass": "77", "hair_color": "blond", "skin_color": "fair", "eye_color": "blue", "birth_year": "19BBY", "homeworld": "Tatooine", "films": [ "A N ...

Retrieving, storing, and utilizing JSON variables in Express

I've been struggling to grasp the concept of accessing and processing data using different HTTP methods like get, put, post. Currently, I have managed to retrieve JSON data and store it in a global variable. var pokemonsData; fetch('https://raw ...

Creating a conditional query in Mongoose: A step-by-step guide

The code below functions without any query strings or with just one query string. For example, simply navigating to /characters will display all characters. However, if you specify a query string parameter like /characters?gender=male, it will only show ma ...

Merge functions that execute identical operations

I find myself in a situation where I have two functions that do very similar tasks, but on different elements. Initially, I only anticipated having these two functions, but now I realize I'll need to add more. This will result in a lot of repetition. ...

Automatic session destruction in Laravel 5.1 when using AngularJS is a seamless process

Session in laravel 5.1 automatically ending My server side is Laravel and client side uses AngularJS. Even though I'm storing session data in root scope and window Storage for the front end, my application sometimes experiences random session destru ...

Finding documents in MongoDB where the size of an array exceeds 1

Looking to retrieve documents with an array size greater than 1 in my MongoDB collection Here is a snapshot of my collection: { "_id" : ObjectId("5eaaeedd00101108e1123452"), "type" : ["admin","teacher" ...

What is the process for retrieving the updated document from the findOneAndUpdate function?

Utilizing MongoDB with Node.js, I installed the MongoDB module using npm install mongodb. I encountered an issue where updating an existing document did not return the updated document; instead, it returned the original one. Even after setting the returnN ...

Retrieve the specific key or object number by conducting a search in JavaScript

I am faced with the challenge of editing a large XML file by searching for a specific keyword within the "event name" field and changing the corresponding "active" value to either 1 or 0. The structure of the data file is as follows. I have managed to modi ...