Implementing changes in the last loop iteration to impact the final result in Vue

Having recently delved into Vue, I'm having trouble figuring out how to solve this issue. Let me begin by showing you the code snippet followed by explaining the problem at hand. Currently, I am utilizing Vue-Good-Table for this project.


methods:{
  getTotals(){
    var self = this;
    var new1=[];
    this.$http.get('http://localhost:3000/api/purchases')
    .then(function (response) {
      console.log("response.data value")
      console.log(response.data)
        for (var i = 0; i < response.data.length; i++) {
           var item1=JSON.parse(response.data[i].pur_items);
             console.log("item1 for index i time" +i)
              console.log(item1)

              new1=item1

        }
       console.log("final output")
       console.log(new1)


    })

},

Upon reviewing the console log from the 'for loop', https://i.sstatic.net/a9ayt.png it seems that instead of receiving 5 arrays in the final output stored in 'new1', only 2 arrays are displayed during the last iteration. Any suggestions on what I may be doing incorrectly?

Answer №1

It is expected that the array of the last iteration will be contained in new1 based on your code.

To resolve this, consider replacing new1 = item1; with new1 = new1.concat(item1);

If you want to learn more about the methods available in the Array prototype, I suggest checking out the documentation on the Mozilla Developer Network website.

Answer №2

Make sure to concatenate the arrays instead of replacing them during each iteration.

methods: {

  getTotals() {
    var self = this;
    var new1 = [];
    this.$http.get('http://localhost:3000/api/purchases')
      .then(function(response) {
        console.log("response.data value")
        console.log(response.data)
        for (var i = 0; i < response.data.length; i++) {
          var item1 = JSON.parse(response.data[i].pur_items);
          console.log("item1 for index i time" + i)
          console.log(item1)

          new1 = new1.concat(item1)

        }
        console.log("final output")
        console.log(new1)


      })

  },

},

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

Tips for handling tasks with javascript in mongodb

The Mongo database is set up with a sharding structure of 3 Shards named TestSharding. Additionally, the script for this configuration can be written in JavaScript. I am tasked with developing a program that identifies whether a file is in .json or .csv f ...

Media queries in CSS appear to be dysfunctional when used on Microsoft Edge

@media (min-width: 992px) and (max-width: 1140px) { .mr-1024-none { margin-right: 0px !important; } .mt-1024 { margin-top: 1rem !important; } .d-1024-none { display: none !important; } } Utilizing the ...

Steps for adjusting the status of an interface key to required or optional in a dynamic manner

Imagine a scenario where there is a predefined type: interface Test { foo: number; bar?: { name: string; }; } const obj: Test; // The property 'bar' in the object 'obj' is currently optional Now consider a situatio ...

Difficulty in comparing passwords using bcrypt encryption method

As a beginner in express js, I have successfully implemented the register functionality in my app. However, I am facing an issue with the login process. I am trying to compare the password stored in the database with the one provided by the user using bcry ...

Show a pair of pictures every X hours using Javascript

Trying to create a code that displays different pairs of images each day, but struggling to make it select them randomly. Instead, the code currently just goes through the array one by one. I'm not great with Javascript and haven't found a way to ...

Adjust the height of a sibling div using JavaScript with mouseover event

I need assistance with creating an audio visualizer effect where on mouseover, "this" div becomes the tallest one and the other divs adjust their heights accordingly. How can I specify the specific height for each sister div to change to? Code window ...

Loading slides in bxSlider using ajax

Is there a method to dynamically insert a slide into bxSlider via ajax without affecting its smooth transition? I am looking to initially display the contents of only one slide upon page load, and then have subsequent slides loaded when the next or previo ...

Pinia store successfully implemented following the state invocation

Currently, I am in the process of developing a vuejs 3 application using the composition API. Within this application, I have implemented 2 separate stores: the userStore which manages user authentication information such as userid and jwt after login, an ...

Organize data by multiple criteria using List.js

Attempting to configure the list.js plugin to allow sorting based on multiple values. Specifically, the goal is to sort by category first and then alphabetically by title within each category. See a demo here: http://jsfiddle.net/8E7cH/ This functional ...

Mongoose: No documents are being returned by the .find() method

UPDATE : Similar question posted here: Trouble with Mongoose find() method I'm still new to working with nodejs and nosql databases. Today, I am building an API that retrieves data from my user collection which currently has two entries : The issue ...

Is it possible to utilize Ajax submit requests within a (function($){...}(jQuery)); block?

As a PHP developer with some knowledge of JavaScript, I am currently using AJAX to send requests to the server. I recently came across the practice of enclosing all code within an anonymous JavaScript function like: (function($){ //code here }(jQuery)). Fo ...

guide on creating a simple line highchart using JSON data

Here is the JSON data I have: {"09/02/2014 15:36:25":[33.82,33.42,40.83],"08/11/2014 16:25:15":[36.6,33.42,40.45],"07/30/2014 08:43:57":[0.0,0.0,0.0],"08/12/2014 22:00:52":[77.99,74.1,80.12],"08/12/2014 21:19:48":[56.91,63.23,52.42],"07/23/2014 13:37:46": ...

Are several UDP sockets open across various ports?

I'm trying to get the port of a receiving server using the following code snippet: var dgram = require("dgram"); var start = 27015; for(var i = start; i < (start + 100); i++) { var server = dgram.createSocket("udp4"); server.on("message ...

"Bower fetches and installs specific versions of packages from the repository

I'm currently using npm 3.3.6 and bower 1.6.8 on Windows 10. Whenever I attempt to install a package like jquery or framework7, it ends up downloading and installing an archived version of the package. Here's an example: > bower install jquer ...

Utilizing Ajax to dynamically update the content of a div element

As a newcomer to Ajax, I am trying to use xmlhttprequest to dynamically change the content of a div by fetching HTML from different URLs. However, my code doesn't seem to be working as expected. Can someone help me identify what I might be doing wrong ...

Redirecting to new page after submitting form using Ajax

I'm having some trouble with my HTML form submission using JQuery and AJAX. After successfully submitting the form, I want to display a modal and then redirect to another page based on certain conditions. I've written the logic in my JS file wh ...

Guide on creating multiple instances of vue-multiselect with a simple button click

I am trying to implement a vue-multiselect dropdown with the addition of a new dropdown upon clicking an "add more" button. However, I am currently unsure of the best approach to achieve this. Problem/Question: When adding 2 dropdowns, if the same option ...

Exploring the world of data manipulation in AngularJS

Seeking to comprehend the rationale behind it, I will share some general code snippets: 1) Fetching data from a JSON file using the "loadData" service: return { myData: function(){ return $http.get(path + "data.json"); } } 2) ...

Encountered Runtime Error: TypeError - Carousel triggering issue with reading properties of null (specifically 'classList') in Tailwind Elements

Currently, I am encountering the error message: Unhandled Runtime Error TypeError: Cannot read properties of null (reading 'classList') while utilizing the Carousel component. The problem arises when I attempt to populate the carousel with images ...

What could be causing the issue with setting a value for a JSON array in the following method?

Consider this piece of code that I'm currently working with: compareList[productName] = productID + ',' + productHref; console.log(productName + ' ' + productID + ' ' + productHref + ' ' + compareList.length); ...