Having difficulty fetching information from the array

Here is an array that I need to work with:

[
   {id: "1280-00-477-5893-OkqcPp3xJwfgmNinwGsKZmAa8xt1-1514575144592", name: "Cancelled -> Replaced by 1280005462575", price: "$324", imgsrc: "https://firebasestorage.googleapis.com/v0/b/honeyb…=media&token=3acd47c0-773a-48c1-8956-9a025769b91e", availableqty: "4", …}
   {id: "1510-00-140-1627-OkqcPp3xJwfgmNinwGsKZmAa8xt1-1514546926962", name: "AIRPLANE UTILITY", price: "$890", imgsrc: "https://firebasestorage.googleapis.com/v0/b/honeyb…=media&token=01267792-8f7f-40a6-921b-699e4366e5cb", availableqty: "65", …}
]

The goal is to use the id of each object and query the firebase database for more details.

  $('.checkout').click(function(){

// Check if user is authenticated

 firebase.auth().onAuthStateChanged((user) => {
    if (user) {
        var userId = firebase.auth().currentUser.uid;
        for (var i = 0; i < cartarry.length; i++) {
                    var id = cartarry[i].id;
                    var finalqty = cartarry[i].quantity;
                    var price = cartarry[i].price;
                    var itemref = Cataloguedatabase.ref('/Listings/' + id).once('value', function(snapshot) {
                        var listingdetail = snapshot.val();
                        // Calculate remaining quantity after order
                        var availableqty = parseInt(listingdetail.Ava_QTY);
                        var orderedqty = parseInt(finalqty);
                        var qtyleft = availableqty - orderedqty;
                        console.log("Ordered Quantity: ", orderedqty)
                        console.log("Available Quantity: ", availableqty)
                        console.log("Remaining Quantity: ", qtyleft)
                        console.log("Price: ", price)                           

                    })
    }

} else {

    window.location = "../html/auth.html"
}

})

})

The code functions as intended, but it only displays the last array value for price and ordered quantity. Instead of showing $324 and $890, it repeats $890 twice. What am I doing incorrectly and how can I resolve this issue?

Answer №1

It is advisable to use let instead of var when declaring variables.

let id = cartarry[i].id;
let finalqty = cartarry[i].quantity;
let price = cartarry[i].price;

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

What are the steps to incorporating HTML code into JavaScript?

Can I insert HTML elements into the view using JavaScript? I am hoping to achieve something like this: <script> <% for @m in @messages %> <h1>i</h1> <% end %> </script> I need it to work seamlessly with Ruby. Not s ...

Proper technique for efficiently inserting multiple records into Mongodb using Node.js

What is the most effective way to perform bulk inserts into MongoDB using Node.js or any other database? Here's an example code snippet that I've written, but I suspect it may have a flaw as db.close() could be executed before all asynchronous c ...

When I set the width of my script to 100% in CSS, it causes the width to become distorted

I encountered an issue with my Div Slider that swaps out Divs on click. When I modified the CSS to include the following: .hslide-item {width: 100%}; The script started ignoring the entire div width. I am looking for a solution where the .hslide-item ca ...

Converting character array to a double after reading from a file

Currently, I'm in the process of reading a file that contains numbers separated by spaces. My goal is to store these numbers into an array of integers, but unfortunately, I seem to be doing something incorrectly because all I'm getting are zeros ...

Why does the Next.js GET index request keep fetching multiple times instead of just once?

Currently, I am encountering an issue while working on a tutorial app with Next.js. One of my components is not rendering due to what seems like multiple executions of a simple GET request for an index page. The problem perplexes me, and I need some assist ...

Displaying multiple div elements when a button is clickedLet multiple divs be

ISSUE Hello there! I'm facing a challenge where I need to display a div when a button is clicked. The issue arises from having multiple divs with the same class, making it difficult for me to target each individual div... Image1 Image2 Desired Outco ...

What is the correct method for iterating through this array of objects and eliminating those with either null or empty item.text values?

Currently, I am working with the following Array: const contactInfo = computed(() => { return [ { id: 'address', icon: 'detail/clubLocation', text: `${props.data.contactInfo.address}` ...

Unable to accurately compare the original array with a deep clone

I am currently testing the similarity between my deep clone of an array and the original object (using jQuery). Here is the method I used to clone it: self.slides = jQuery.extend(true, {}, parent.modules[self.moduleId].composed); However, I have noticed ...

Tips for triggering a method when clicking instead of using v-for in Vue.js

I need help arranging an array of objects based on their ratings. Currently, I am able to display the items from highest to lowest rating using the v-for method. But, I would like to first display the objects in their original order and then have a button ...

Assigning a full array to a single element in C++

Currently in the process of developing a set of bingo cards. This set includes information such as the number of cards, the size of each card, and the maximum number that can appear on the cards. The goal is to generate n arrays (cards) containing unique ...

Determine overlapping ranges in JavaScript by comparing the "from" and "to" variables for

While working on my angular app, I encountered a seemingly simple task that turned out to be surprisingly complex. I have come up with a few solutions, but none of them seem perfect. The issue at hand is that I have an array containing possible unlimited ...

Conceal the div class upon clicking it

I'm dealing with a list of videos and I need to hide the class when it's clicked. Check out this sample HTML output: <div id="primary-video"> <iframe id="video" width="100%" height="auto" src="https://www.youtube.com/embed/test" fra ...

Send data without needing to navigate away

Is there a way to submit a form without redirecting the page? The form is being submitted to a third party, so I am unable to make changes in PHP. I would like to submit the form without visiting the third party page. After successful submission, I want ...

Consolidate a Node Typescript project into a single executable JavaScript file

Is it possible to consolidate a whole TypeScript project into a single executable js file? For instance, running node app.js where app.js is the compiled project. I've experimented with the compilerOption outFile, but haven't been able to gener ...

Is there a way to adjust the size of a specific section within an SVG

My SVG image consists of 2 parts: ____________ | | | | p1 | p2 | |____|______| I am looking for a way to save the width of part p1 and only scale the width of part p2 on the horizontal scale. Can someone please suggest where I can find inform ...

Something seems off with the way the jQuery auto correction feature behaves with duplicated input

Incorporating a jQuery script for auto-correcting form input has proven to be quite effective in my project. For instance, if someone inputs "abc" as their initials, the field will automatically correct it to A.B.C. While these scripts function perfectly, ...

Using jQuery combogrid to automatically target and populate input box upon row selection

I have implemented combogrid functionality from https://github.com/powderblue/jquery-combogrid to display suggestions while typing. $(".stresses").combogrid({ url: '/index/stresssearch', debug: true, colModel: [{'col ...

Can the state be determined by the presence of other objects in the state?

Currently, I'm delving into the world of ReactJS by constructing a personalized launch page. Brace yourself for a somewhat casual explanation. Within my primary app.js file, I've set up the initial state of the application with some data like th ...

Add a fresh column in the table that includes modified values from an existing column, affected by a multiplication factor provided through a text input

I'm currently working on a Laravel website where I have a pricing table sourced from a database. The Retail Price column in this table serves as the base for calculating and populating a Discount Price column using a multiplier specified in a text inp ...

Having trouble retrieving the API URL id from a different API data source

For a small React project I was working on, I encountered a scenario where I needed to utilize an ID from one API call in subsequent API calls. Although I had access to the data from the initial call, I struggled with incorporating it into the second call. ...