Retrieve an object that includes a property with an array of objects by filtering it with an array of strings

I have a large JSON file filled with data on over 300 different types of drinks, including their ingredients, names, and instructions. Each object in the file represents a unique drink recipe.

Here is an example of how one of these objects is structured:

    "strCategory": "Beer",
    "strDrink": "110 in the shade",
    "strAlcoholic": "Alcoholic",
    "dateModified":: "2016-02-03 14:51:57",
    "strInstructionsIT": "Riempi un bicchierino di tequila.\r\nRiempi un boccale di birra con la birra chiara.\r\nMetti il bicchierino nella birra e bevi velocemente.",
    "idDrink": "15423",
    "strDrinkThumb": "https://www.thecocktaildb.com/images/media/drink/xxyywq1454511117.jpg",
    "strCreativeCommonsConfirmed": "No",
    "strGlass": "Beer Glass",
    "Ingredients": [
      {
        "Ingredient": "Lager",
        "Measurement": "16 oz "
      },
      {
        "Measurement": "1.5 oz ",
        "Ingredient": "Tequila"
      }
    ],
    "strInstructionsDE": "Shooter tröpfchenweise in ein Glas geben. Mit Bier füllen.",
    "strInstructions": "Drop shooter in glass. Fill with beer"
  },
  {
    ...
  }

One specific requirement I have is to filter the drink objects based on user-provided ingredients. The user may enter an array like this:

let Ingredients_Entered_By_User = ["Vodka", "Rum", "Lemonade"];

The goal is to find all drink recipes that contain all of the specified ingredients entered by the user. It doesn't have to be an exact match, but each drink must include all of those selected ingredients to be included in the filtered results.

Answer №1

Utilize various array methods

const data = [{
    "Ingredients": [
      {
        "Ingredient": "Malibu Rum",
        "Measurement": "1/2 oz "
      },
      {
        "Ingredient": "Light Rum",
        "Measurement": "1/2 oz "
      },
      {
        "Ingredient": "Rum",
        "Measurement": "1/2 oz"
      },
      {
        "Measurement": "1 oz ",
        "Ingredient": "Dark Creme De Cacao"
      },
      {
        "Measurement": "1 oz ",
        "Ingredient": "Cointreau"
      },
      {
        "Ingredient": "Milk",
        "Measurement": "3 oz "
      },
      {
        "Ingredient": "Coconut Liqueur",
        "Measurement": "1 oz "
      },
      {
        "Measurement": "1 cup ",
        "Ingredient": "Vanilla Ice-cream"
      }
    ],
    "strInstructionsDE": "Alle Zutaten vermengen. Mischen, bis alles glatt ist. Auf Wunsch mit Schokoladenraspeln garnieren.",
    "strDrinkThumb": "https://www.thecocktaildb.com/images/media/drink/rvwrvv1468877323.jpg",
    "strCategory": "Shake",
    "strInstructions": "Combine all ingredients. Blend until smooth. Garnish with chocolate shavings if desired.",
    "idDrink": "14588",
    "strCreativeCommonsConfirmed": "No",
    "strInstructionsIT": "Combina tutti gli ingredienti.\r\nFrulla fino a che è liscio.\r\nGuarnire con scaglie di cioccolato se lo si desidera.",
    "dateModified": "2016-07-18 22:28:43",
    "strGlass": "Beer Mug",
    "strDrink": "151 Florida Bushwacker",
    "strAlcoholic": "Alcoholic"
  }]

const ingredients = ["Vodka", "Rum", "Lemonade"]

const selection = data.filter(cocktail => ingredients.every(ingr => cocktail.Ingredients.find(cockIng => cockIng.Ingredient === ingr)))

console.log(selection)

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

combine several arrays next to each other based on a specified key

I have a collection of three sets, each containing three elements: Set1 = [[apple, 2, 4], [banana, 5, 5], [cherry, 4, 1]] Set2 = [[banana, 1, 7], [cherry, 3, 8], [date, 5, 4]] Set3 = [[apple, 5, 2], [banana, 0, 9], ...

"Is there an issue with body parsing in Node.js where newline characters in the request body are not being escaped

Currently, I am in the process of building a basic reverse proxy to forward client requests to a remote server. To achieve this, I have incorporated body-parse along with express.js for Node server, enabling me to transmit the body of the request. Howeve ...

When using VueJs, the input value may not clear upon pressing the ESC key for the first time

When I press the ESC key, my input should clear. However, I am experiencing a bug where the input is not cleared after the first press of the ESC key; it only clears after the second press. Even though the console displays an empty value for the input aft ...

Executing a secondary API based on the data received from the initial API call

Currently, I am diving into the world of RxJS. In my project, I am dealing with 2 different APIs where I need to fetch data from the first API and then make a call to the second API based on that data. Originally, I implemented this logic using the subscri ...

Encountering an error when attempting to iterate over an undefined property using an API

I am trying to fetch all classes and their assignments from Google Classroom. I successfully used Google's example code for listing the classes, but had to write my own code for listing the assignments. While the code runs as expected and lists the as ...

Keep JS Accordion open when links are clicked

Utilizing PHP, I am fetching items from a database and creating an HTML table to display each item. Adjacent to the HTML table, there is a side menu with an accordion function implemented in JavaScript. Within each accordion section, there are links for ...

Troubleshooting multiple element visibility problems with jQuery

Please take a look at the code snippet below. $(document).ready(function(){ $(".like-btn").hover(function() { var rowid = $(this).attr("data-rowid"); $(".reaction-box[data-rowid='" + rowid + "']").fadeIn(100, function() { $(".reaction ...

Changing JSON variable letter case to lowercase using C#

Utilizing the JSONPEncoderFactory and JSONPBehavior method has allowed me to incorporate JSONP into WCF seamlessly. Everything is set up correctly and my service successfully returns data without any issues. However, I am faced with the challenge of conve ...

Tips for saving data obtained from an ajax call

My jquery ajax function has a callback that creates an array from retrieved json data. Here's an example: success: function (response) { callback(response); }, The callback function, in this case createQuestionsArray(), populates ...

What is the proper way to retrieve the Nuxt context within the fetch() hook?

Is there a way to access the props within an async fetch() function when also using async fetch(context)? I'm trying to figure out how to work with both simultaneously. ...

transmit JSON array data to recipient using PHP mailer

I'm facing an issue with my PHP form mailer that uses JSON and AJAX to send data array. The problem is that the mail is being sent without the data, even though I have validated the JSON string to confirm it contains the necessary information. Below ...

Exploring AngularJS tab navigation and injecting modules into the system

Two separate modules are defined in first.js and second.js respectively: first.js var app = angular.module('first',['ngGrid']); app.controller('firstTest',function($scope)) { ... }); second.js var app = angular.mo ...

When using v-select to search for items, the selected items mysteriously vanish from

I recently worked on a project where I encountered a similar situation to the one showcased in this CodePen. Here is the link to the specific CodePen One issue I faced was that the selected items would disappear when performing an invalid search. After i ...

unable to display friends' names in chat

Can someone assist me with an issue I'm facing in my chat application? Whenever I try to display a friend's name on the chat, the app crashes. If I remove the part where the friend's name is displayed, the messages show up fine. However, as ...

Combining arrays encoded in JSON format

Consider the following array examples: $array1 = [ 'test' => json_encode([ 'key1' => 'val1', 'key2' => 'val2', 'key3' => 'val3' ]) ] Now, let's ...

How can I incorporate dynamic data to draw and showcase graphs on my website using PHP?

I am currently working on a project that requires displaying a graph showing the profit of users per day. Currently, I have implemented code to display a static graph on my page. <script type="text/javascript" src="https://www.google.com/jsapi">< ...

What is the best way to utilize a JavaScript variable as a background within an inline style sheet?

I have a fun project for this evening - I am trying to make my website load a different background image every time the page is refreshed. Earlier on in this project, I managed to make the background interact with window size and screen resolution similar ...

Issues Arise when Attempting to Upload Files to AWS S3 Using Node.js as

Utilizing this AWS S3 NPM Package for managing S3 uploads from my Express server has presented me with a puzzling situation. The uploader fails to trigger the end function. var key = utils.createID(Date.now()); var s3 = require('s3'); var client ...

Transforming a hierarchical JSON structure into a tabular format with multiple levels of nesting

Our dataset contains json fields with repetitive sections and potentially infinite nesting possibilities. Taking inspiration from Google BigQuery's repeated fields and records feature, I decided to restructure the data into repeated record fields for ...

Can Jquery be used to swap out specific li content?

<div class="widget_ex_attachments"> <ul> <li> <i class="fa fa-file-word-o"></i> <a href="uploads/2014/09/Parellel-universe.docx">Parellel universe</a> </li> ...