Attempting to iterate over elements within an object labeled as strIngredients 1-15

    event.preventDefault();

    $('#mainContent').empty();

    $.ajax({
        url: randomDrinksURL,
        method: 'GET'
    }).then(function (response) {
        console.log(response);
        var mainContent = $('#mainContent');
        mainContent.append(`
        <img src='${response.drinks[0].strDrinkThumb}'>
        <p>${response.drinks[0].strDrink}</p>
        <p>${response.drinks[0].strMeasure1} of ${response.drinks[0].strIngredient1}</p>
        <p> ${response.drinks[0].strInstructions}</p>
        `);
    });

This data provides details for various ingredients and measurements from 1 to 15. I am currently exploring ways to iterate through them dynamically, ensuring it stops when a value is null.

I attempted to use a for loop but encountered difficulties. Any suggestions or guidance on this matter would be greatly appreciated!

Answer №1

Is there a possibility for something like this to work in this scenario?

let html = `
        <img src='${response.drinks[0].strDrinkThumb}'>
        <p>${response.drinks[0].strDrink}</p>
        `

for (var i = 1; i<= 15; i++) {
  let ingredient= "strIngredient" + i;
  let measure= "strMeasure" + i;
  if (response.drinks[0][measure] && response.drinks[0][ingredient]) {
    html += `<p>${response.drinks[0][measure]} of ${response.drinks[0][ingredient]}</p>`
  }
}

html += `<p> ${response.drinks[0].strInstructions}</p>`

mainContent.append(html)

modified included a condition for null values

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

The element is not defined in the Document Object Model

There are two global properties defined as: htmlContentElement htmlContentContainer These are set in the ngAfterViewInit() method: ngAfterViewInit() { this.htmlContentElement = document.getElementById("messageContent"); this.htmlContentCont ...

Executing the AngularJS nested controller only once

I am still new to Angularjs and just started working on an app that has several "projects" each with a local menu displayed on specific pages. The main navbar with footer is located in the Index.html: <body ng-app="ysi-app" ng-controller="MainControlle ...

What should be the response to send back following an Ajax call in asp.net

Once the ajax call is finished and the model has been successfully posted to the controller, what should be returned by the controller? In this scenario, my intention is simply to add an item to the wishlist without any redirection. ...

Generate real-time dynamic line charts using data pulled directly from a MySQL database

I am in search of guidance on developing a real-time line chart that can dynamically update based on data fetched from MySQL. I need an example or reference on how to achieve this functionality without having to refresh the webpage every time new data is ...

Passing a particular method of a specific instance as an argument

I am interested in creating a class that allows me to specify "For instance a1 of A, you will call the function computeValue() of a specific instance b1 of B when the value is needed". It's important for me to indicate which method of which instance w ...

To securely insert a PHP variable into a MySQL database through AJAX without revealing the value in the DOM

I am currently working on developing a straightforward To Do app that integrates with Facebook. My goal is to allow users to create a new To Do list and store it in the database (for this, I utilize Ajax). Below, you will find the code snippet along with ...

I am interested in using the split method to separate and then mapping an object in JavaScript

Need assistance on separating an array using the split method. The array contains objects with properties such as name, course1, course2, and course3. Only the courses with text in their content along with a plus sign should be separated into an array usin ...

What is the best way to click on a particular button without activating every button on the page?

Struggling to create buttons labeled Add and Remove, as all the other buttons get triggered when I click on one. Here's the code snippet in question: function MyFruits() { const fruitsArray = [ 'banana', 'banana', & ...

Promises and Their Valuable Variables

Recently I began learning JavaScript and I'm encountering some confusion. Here's the code snippet that is causing me trouble: api.posts .browse({ limit: 5, include: 'tags,authors' }) .then(posts => { posts.forEach(post =&g ...

I am attempting to develop a basic express application, but it doesn't appear to be functioning as expected

I am currently working on developing a straightforward express application. However, I am facing network errors when trying to access it through my browser at localhost:3000 while the application is running in the console. The root cause of this issue elud ...

Learn how to establish a state using an array and effectively utilize the setState() method in React

For my latest project, which is API based, I am working with arrays that contain sub-arrays. How can I define a state with an array and utilize the setState() method to work with the entire array? ...

Loop through the JSON data to generate clickable links in the innerHTML

I've been searching through various resources for a solution to the issue I'm facing. My goal is to iterate through a JSON object and extract all the ids and corresponding dates from each top_worst section. The structure of the JSON data is as fo ...

Display various elements depending on the size of the screen within Next.js

My goal is to display a component differently depending on whether the screen width is less than 768p or not. If the width is under 768p, I want to show the hamburger menu. Otherwise, I want to display the full menu. This is the code snippet I am using. ...

No data is being recorded in the Firestore database

This component in nextjs is designed to write data to a firestore database after the user clicks a button. Unfortunately, Firebase seems to be having trouble writing the data, even though the alert message following the supposed data dump is successful. I ...

Mongoose fails to save due to an error stating "undefined id"

Having some trouble with the Mongoose save function... In my user model file: const mongoose = require('mongoose'); const Schema = mongoose.Schema; const User = mongoose.model('User', { name: Schema.Types.Mixed, gender: String, ...

Instead of returning a JSON result, the MVC controller method called from AngularJS is returning the view HTML

Within the HomeController, I have the following method, [HttpGet] public ActionResult GetStudents() { Student std1 = new Student(); List<Student> stdlst = new List<Student>(); std1.Id = 1; ...

Using AngularJS to bind elements within elements

Feel like I might be overlooking a simple solution here, but I'm facing an issue: <h4 ng-bind="example.heading"> <small ng-bind="example.subheading"></small> </h4> This code doesn't seem to work - if ng-bind replaces ...

I could really use some assistance with this project for my friend

Whenever I click on the image, it only displays two out of the three possible alerts. How can I make it show all three? Here's my code: <!DOCTYPE html> <html> <head> </head> <body> <img src="http://www.build ...

The tooltip in a scrollable container of Highcharts moves along with the content as it scrolls

I am currently facing an issue with my Highcharts instance that is displayed within a scrollable container. In addition, I have set the tooltip.outside option to true so that the tooltip always appears on top even if it exceeds the chart svg. The problem ...

Update the href attribute with values from the form fields

My current project involves creating a form with 5 input fields: Service type Number of days Number of children Number of adults I want to dynamically change the value of a button based on these variables using JavaScript. Here is my code so far: JS ...