Exploring the contents of variables within the forEach iteration

One issue I've encountered involves accessing variables from a forEach loop that iterates over an array of objects, and trying to use those variables outside the loop. I attempted to declare variables and assign them values from the loop, but I found that it only returned the first value.

let bestPrice;
let injectInstruments;
allInstruments.forEach(function (instrument) {
    
    let price = instrument.price;
    let type = instrument.type;
    let description = instrument.description;
    let picture = instrument.picture;
   
     injectInstruments =instrumentsContainer.innerHTML= `<div  hidden 
    instrumentType='${type}'class="box instrument" price="${price}">
        <img class="instrument-image" src="${picture}" alt="">
       <h6 class="price">${price}</h6>
        <p class="instrument-description">${description}</p>
    </div>`
   bestPrice=price
})
console.log(injectInstruments);
console.log(bestPrice);

Answer №1

Problem

  • bestPrice gets overwritten in each iteration.
  • instrumentsContainer.innerHTML is also overwritten in each loop.
  • There is no need to call injectInstruments to insert HTML as using .innerHTML = '' will suffice.
  • The line
    injectInstruments = instrumentsContainer.innerHTML='<div ...>'
    contains three equals signs, causing a syntax error.

Resolution

  • Consider using .insertAdjacentHTML() instead of .innerHTML. The former adds HTML content to a container, while the latter replaces the entire container's content.
  • If the goal is to only access prices, store them in an array.

// Obtain the container <div>
const instrumentsContainer = document.querySelector('div');

const allInstruments = [{
    price: 100,
    type: 'something',
    description: 'lorem ipsum',
    picture: './image1.jpg'
  },
  {
    price: 200,
    type: 'something2',
    description: 'lorem ipsum2',
    picture: './image2.jpg'
  },
];

// Array to store prices
let bestPrices = [];
  
function myFunction() {
  allInstruments.forEach(function(instrument) {

    let price = instrument.price;
    let type = instrument.type;
    let description = instrument.description;
    let picture = instrument.picture;

    // HTML content
    let html = `<div instrumentType='${type}' class="box instrument" price="${price}">
        <img class="instrument-image" src="${picture}" alt="${picture}">
       <h6 class="price">${price}</h6>
        <p class="instrument-description">${description}</p>
    </div>`;

    // Insert the generated HTML at the end of the <div>
    instrumentsContainer.insertAdjacentHTML('beforeend', html);

    // Add the price to the array
    bestPrices.push(price);
  });
}

// Call myFunction();
myFunction();

// Check the array of best prices
console.log(bestPrices);
<div></div>


I personally believe that storing prices in an array is not necessary. If the aim is to find the lowest price, you can achieve this like so:

const allInstruments = [{
    price: 100,
    type: 'something',
    description: 'lorem ipsum',
    picture: './image1.jpg'
  },
  {
    price: 200,
    type: 'something2',
    description: 'lorem ipsum2',
    picture: './image2.jpg'
  },
];

let bestPrice = Math.min(...allInstruments.map(e => e.price));

console.log(bestPrice)

Answer №2

The fluctuating values of bestPrice and injectInstrument are due to their constant change within each loop iteration. To address this issue, consider storing the values in a string array and utilize a debugging method such as iterating through loops to track and monitor the changes.

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

Need to invoke a controller method multiple times? Utilize AJAX for seamless and efficient execution

Apologies if this question seems simple, but I'm struggling to find a solution. I've implemented a straightforward method in a controller: public string ExactSeconds() { string str = DateTime.Now.Second.ToString(); return str; ...

Specify the controller to be used dynamically in an Angular directive

I want to be able to specify the controller that a directive uses by adding an attribute to the element - in other words, dynamically: HTML <div data-mydirective data-ctrl="DynamicController"></div> Angular angular.module('app', [ ...

Ajax encountered a problem while attempting to download the file

I have a situation where JavaScript generates content within a function, and I need to save that content in my downloads folder. However, when I attempt to do so via AJAX, it does not work and no errors are being displayed. Here is the JS code: $.ajax({ ...

Errors are thrown when utilizing hydration with RTK Query

Looking for a solution with my local API and RTK Query, I've encountered an issue when implementing server-side rendering (SSR). Here's the code snippet I'm working with: const api = createApi({ reducerPath: 'data', baseQuery: ...

The distinction between storing data and component data becomes apparent when using Vuex in conjunction with a persisted state

Below is my post.js file in the store directory: import axios from 'axios' import createPersistedState from "vuex-persistedstate" export default { namespaced: true, state: { sample_data: 'Welcome!!', l ...

Retrieve the image by its unique identifier while viewing a preview of the image before it is uploaded

Below is the script I am using to preview an image before it is uploaded. The HTML structure looks like this: <div> <img id="image" src="#"> </div> <input type="file" accept="image/gif, image/jpeg, image/png" onchange="readURL(th ...

What is the best way to extract the image url from a page in WordPress?

Is there a way to extract the image URL in WordPress dynamically for use as a reference in a script? When I use postimage(); it extracts this: <a href="address"> <img width="300" height="300" src="image.png" class="image" alt="" title="LINKING"/& ...

The pagination feature is malfunctioning and is displaying all elements on every page instead of correctly displaying a

I am currently working with BootstrapVue 3 to create a component that uses a b-table. The issue I am facing is with the pagination functionality using b-pagination. My intention was to display only 2 objects per page, but instead of that, all objects are ...

The array exceeded the integer limit when conducting a bitwise left shift operation

Using the bitwise left shift operator, I am generating a numpy array. For instance, creating an array called p with the same shape as matrix a, which is (23,): >>> import numpy >>> a = numpy.array([0,0,0,0,0,0,1,0,1,0,1,1,1,0,0,0,0,0,1, ...

What is the best approach to passing multiple variables to a JavaScript function in HTML/PHP?

Seeking help with calling a javascript function from PHP through embedded HTML code. Below is the script: <script> // THE FOLLOWING JAVASCRIPT FUNCTION REDIRECTS TO EDITUSER.PHP AND PASSES USERID VALUE. function startMaint(mo, yr){ ...

The complete rendering of angular-google-maps is only achieved after resizing the browser

<ui-gmap-google-map center="{latitude: 43.100187, longitude: -77.6329959}" zoom='8'> </ui-gmap-google-map> https://i.sstatic.net/9F2eb.jpg All necessary files were loaded via bower and the dependency was added t ...

Retrieving JavaScript return values in a C# WebBrowser control within a WPF application

I utilized JavaScript injection into WebBrowser control in C# (System.Windows.Controls.WebBrowser) to achieve, <C#> IHTMLDocument2 webdoc = (IHTMLDocument2)webBrowser1.Document; string var = File.ReadAllText("C:/.../Resources/script.txt"); object re ...

How can I avoid C3.js legends from overlapping when hiding or showing a div?

Every time I visit a specific page, a simple chart is automatically generated: function displayOptions() { $("#div1").show(); chartRef.flush(); } function displayChoices() { $("#div1").show(); } $("#div1").hid ...

Ways in which elements can be toggled through jquery or javascript?

There are various words listed below: word1 word2 word3 ... Every word in the list is linked to 1 to 3 examples. When a user clicks on a word, certain actions should take place. I want the examples to display when the associated word (e.g., word1) is c ...

Sending a parameter to a form within Edge Animate

I'm facing an issue where I need to pass a variable to a form from Edge Animate. Here's the current instruction snippet: sym.$("form").append('<iframe width="100%" height="100%" src="login_PRA.php?v_id="vidn frameborder="0" scrolling="no ...

Is there a way to display a different file, such as index.html, based on the screen width?

I'm facing an issue. I have completed a web page (with HTML, CSS, and JavaScript), but now I want to create a mobile version using different HTML files, another index.html file, and a separate CSS file. What changes do I need to make in the main page ...

Issues Persist with Bootstrap Tree View - object passed but no output显示

After going through numerous discussions and solving several issues along the way, I have encountered a major problem where there is no output. As mentioned before, I am utilizing Bootstrap Tree View: To establish the hierarchical structure required for ...

Identifying repeated numbers and displaying the one that occurs most frequently at the top, followed by the remaining

I have successfully identified the duplicate numbers, but now I am looking to take user inputs and determine if there are any duplicated elements in the list. If all values are unique, I want to print out "list has no duplicate values." Otherwise, I would ...

Square-shaped arch chart utilizing Highcharts library

For my project, I have a unique challenge of creating an Arched square chart using High Charts. Despite my efforts, I have not been able to find any suitable platform that demonstrates this specific requirement. The task at hand is outlined as follows – ...

AngularJS Upgrading the Scope with $q

Lately, I've been working on updating code that resembles the following: $scope.arrayOfThings = []; function setArrayOfThings() { thingsService.get().then(function (things) { $scope.arrayOfThings = things; }); } $scope.$on(' ...