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', 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

Prevent unwanted bouncing and zooming on IOS10+ when using routing in VueJS

Currently, I am developing a Vue.js application that integrates with Three.js to display 3D models. I am using Vue.js with Vuetify as the framework and incorporating the Vue.js router. Due to the nature of displaying 3D models, I need to prevent zooming i ...

Customized style sheets created from JSON data for individual elements

One of the elements in the API requires dynamic rendering, and its style is provided as follows: "elementStyle": { "Width": "100", "Height": "100", "ThemeSize": "M", "TopMargin": "0", " ...

Unveiling the Nuxt/Vue frontend and Laravel backend in a local environment using Ngrok

I'm currently working on a local Vue and Nuxt environment that communicates with another local Laravel API route. I'm attempting to expose the ports using ngrok for testing purposes. Within my Nuxt/Vue setup Nuxt configuration // Configuration ...

What could be causing this conflicting behavior with the logical "and" operator?

const {DEMO, PORT, LOCAL} = process.env; const socketAddress = (DEMO & LOCAL)? `http://${hostname}:${PORT}`: `wss://${hostname}`; When DEMO is false, PORT is undefined, and LOCAL is true The hostname being used is http://9f9cbf19.ngrok.io I verified ...

The POST function is executed twice, with the first attempt resulting in a failed API call, but the second attempt is

I am experiencing issues with my subscribe dialog, as it seems to be running the API call twice. The first time it fails, but on the second attempt, it succeeds and inserts the email into the database. This double run is causing errors in my AJAX function, ...

What is causing setTimeout to not function as intended?

I'm having some trouble moving a <div id="box"> whenever my mouse hovers over it. Currently, the element only moves when I trigger the mouseover event on the div itself instead of when my mouse is actually hovering over it. document.getElements ...

Adjust rankings based on the number of upvotes received by a project

I'm facing a challenge with ranking projects based on the number of votes they receive. No matter the vote count, the project always ends up getting ranked as 1. To address this issue, I developed a function to manage the rank count and a return hand ...

Having trouble sending a function as a prop to a child component in React

Something odd is happening, I'm confident that the syntax is correct, but an error keeps popping up: Error: chooseMessage is not a function // MAIN COMPONENT import React, { useState } from 'react' export default function LayoutMain(prop ...

Is there a way to dynamically modify the text of an HTML button element with jQuery?

My goal is to modify the text value of an HTML code using jQuery... <div class="dropdown"> <button type="button" class="btn btn-secondary dropdown-toggle button-text" data-toggle="dropdown><span>1395</span></button> ...

Rendering tables multiple times using VueJS

I need to display only 5 results from an API call, but currently getting more than that. I attempted using an index, but since it's conditional rendering and some results are skipped, the index isn't a viable solution. Is there a way to assign a ...

displaying a pair of distinct elements using React techniques

I need help adding a react sticky header to my stepper component. When I try to render both components together, I encounter an error. To troubleshoot, I decided to render them separately. Surprisingly, when rendering separately, I do not get the "store is ...

Put the code inside a function. I'm new to this

My goal is to encapsulate this code: if($(window).width() > 980) { $(window).on("scroll", function() { if($(window).scrollTop() > 20) { //add black background $(".x-navbar").addClass("active"); $(".x-navbar .desktop ...

In Typescript, it is not possible to assign the type 'any' to a string, but I am attempting to assign a value that is

I'm new to TypeScript and currently learning about how types function in this language. Additionally, I'm utilizing MaterialUI for this particular project. The issue I'm encountering involves attempting to assign an any value to a variable ...

What are the steps to effectively utilize an interface within a TypeScript file that contains its own internal import?

Currently, I am in the process of developing a React JavaScript project using WebStorm and attempting to enable type hinting for our IDEs (including VS Code) by utilizing TypeScript interfaces and JSDoc annotations. Our goal is to potentially transition to ...

``Is there a more SEO-friendly option instead of using an iframe?

I am looking for a solution to easily share my content with other websites without the issues I currently face. Presently, I use an iframe which poses two problems: <iframe width=“540”; height=“700” frameborder=“0” src=“http://www.energi ...

Utilize Page.evaluate() to send multiple arguments

I am facing an issue with the Playwright-TS code below. I need to pass the email id dynamically to the tester method and have it inside page.evaluate, but using email:emailId in the code throws an undefined error. apiData = { name: faker.name.firstNa ...

The function is not valid due to an angular-parse argument

This is my first experience with using angular and parse.com. I encountered the following error: Error: Argument 'eventList' is not a function, got undefined when attempting to execute the following angular code: var main_app = angular.mod ...

Troubleshooting TypeScript when importing external JavaScript: Module not found or no type declaration file available

I recently acquired a VueJS admin template built in JS and am looking to integrate it into my existing TS application. However, when I attempt to transfer the components, views, and other elements, I encounter the following error message. Is there a way to ...

Recognizing JavaScript in Intellij IDEA within a script tag that does not specify the type as "text/javascript"

Using the MathJax javascript library has presented a challenge for me. Whenever I make changes to the MathJax configuration, I encounter issues because it is written in javascript but its type is labeled as "text/x-mathjax-config". This causes Intellij Ide ...

What could be causing my controller to show {{message}} instead of the message that was set up in the configuration

<!DOCTYPE html> <html> <head> <script src="js/angular.js"></script> <script src="js/Script.js"></script> </head> <body ng-app="LoginPage" ng-controller = "LoginPageController"> <form ...