What is the best way to loop through JSON data obtained from a fetch() request and incorporate it into chart data?

I've been working on pulling JSON responses from an API to use in a Chart.js chart within my Vue component. Here's the JavaScript code snippet I'm using:

import LineChart from './LineChart.js'
  export default {
      name: 'Chart',
      components: LineChart,
      data () {
        return {
          loaded: false,
          stockData: {
            labels: null,
            datasets: null
          }
        }
      },
      async mounted () {
        this.loaded = false
        try{
          const response = await fetch('http://localhost/AAPL')
          const stock = await response.json()
          console.log(stock)
          let annual = stock.Earnings.Annual
          for(let i of annual){
            this.stockData.labels.push(i.date)
            this.stockData.datasets.push(i.epsActual)
          }
          this.loaded = true
        } catch (e){
          console.error(e)
        }
      }
  }

However, I encountered an error message stating:

Chart.vue?36ee:38 TypeError: annual[Symbol.iterator] is not a function

Does anyone have suggestions on how to successfully incorporate this data into the chart?

Answer №1

When working with JavaScript, it's important to understand the various types of loops available. If you're encountering a message related to iterations, it may be due to annual being an object that lacks a custom iterator.

1) The for ... of loop is designed for iterating over objects that implement the iterable protocol, such as arrays or array-like structures, or objects with a custom iterator.

2) On the other hand, for ... in loop is ideal for looping through object keys and array indexes.

Consider using for ... in in your code:

for(let key in annual){
    this.stockData.labels.push(annual[key].date)
    this.stockData.datasets.push(annual[key].epsActual)
}

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 is the reason for the 'admin' page not being displayed?

After reading the MEAN MACHINE Book and following the instructions on Routing Node applications [pg - 36], I encountered an issue. The express.Router()⁴⁸ functions as a mini application where you can define routes. Let's see an example by adding ...

Which is better: TextNode or textContent?

What are the benefits of creating a TextNode and then appending it to an HTML element rather than just setting its textContent directly? Imagine you have a specific span element. var span = document.getElementById('my-span'); If you want to up ...

Handling complex JSON data in KendoUI Grid with varying keys

I have come across a challenging issue with a complex SLC loopback query and the JSON format it returns. Despite my best efforts to find a solution, I seem to be struggling to grasp some of the answers or perhaps I am approaching the problem from the wrong ...

What is the best way to retrieve JSON key values in PHP?

How can I access all the key values from this JSON object using PHP? Here is my PHP code: <?php $json = json_decode('{ "data": { "after": [{ "google.com": "35" }, { ...

Warning: An unexpected issue occurred due to an invalid integer being entered as Not a Number (NaN

I've encountered an issue trying to pass data into the "amount" parameter. From the client, I'm sending the "price" to the server successfully. Upon checking the console output, I see the correct information is being received. The typeof check ...

Dealing with the challenge of managing multiple instances in a setup involving Ajax long polling (comet) and PHP on Lighttpd v1

I am a newcomer to this platform, so I hope to provide all the necessary details about my question. I have been attempting to set up a mechanism for "new message arrived notification" using long polling. Currently, I am triggering the polling request thro ...

What are the best ways to manage a hefty dropdown list?

Currently working with VB.NET/asp.net, I am faced with a page containing a Formview. Within the Insert and Edit templates, there are numerous dropdownlists for both Depts and People. Each of these templates is divided into multiple sections, with around 3 ...

Unable to display the string following a space in the value attribute of an hbs file

<input type="text" class="form-control" id="exampleInputEmail2" name="productName" value={{product.productName}} > When I input 'Smart Phones' into product.produc ...

Creating and utilizing JSON data in the KAFKA platform

We have decided to integrate Apache Kafka 2.10 into our project and facilitate communication using JSON objects between the producer and consumer modules. In order to achieve this successfully, I believe it is essential to: Create a custom serializer to ...

What are the steps for integrating Proguard with Jersey?

Looking to integrate Jersey with Scala using a modified version of SJersey found at this GitHub repository, and applying obfuscation with ProGuard. I have included the following configurations: -keepattributes SourceFile,LineNumberTable,*Annotation*,Encl ...

The functionality of jQuery is limited when trying to implement the .has() method

I have a jQuery code snippet that I am having trouble with function removePreloader() { jQuery('ul.woocommerce-error').has('li').jQuery("#preloader").css("display", "hidden"); } This function is triggered by jQuery('form[nam ...

Using Regex and Javascript to extract the base URL from a string

I am attempting to extract the base URL from a string without using window.location. It must eliminate the trailing slash It must be done using regex instead of New URL It should handle query parameters and anchor links In essence, all of the following ...

Tips for showcasing individual product information on your e-commerce site using React-js and React-Router-dom

As I work on developing an e-commerce platform, my goal is to create a functionality where users can view detailed information about a specific product by clicking on it. To achieve this, I am using React.js along with react-router-dom. Can anyone guide me ...

What is the best way to utilize ajax and javascript for creating a dynamic image gallery on a website

I am looking to create an image portfolio that launches when a user presses a thumbnail. The code for building the portfolio only executes upon pressing the thumbnail. Here is my current setup. Essentially, I want to incorporate something like this into m ...

javascript problem with class method for loading json file

I've encountered an issue with my class setup below. Despite most things working, the console keeps throwing an error when json.onload is triggered. The error message reads "Uncaught TypeError: Cannot read property of 'push' of undefined". ...

Unable to resolve the @fontawesome all / fontawesome-free issue

Vue.js 2 is the framework I am working with, and I recently added some mdi-icons to my App.vue file. This addition resulted in a new error popping up when I attempted to serve my project. Despite trying various commands, I have been unable to resolve this ...

Transform the email into an encrypted format, as the attached email is not functioning properly

I am currently attempting to dynamically change an email's href attribute to a crypted email using jQuery. However, upon utilizing the prop function in jQuery for this purpose, I have encountered an issue where the link becomes unclickable. The final ...

Modifying the font style within an ePub document can affect the page count displayed in a UIWebView

Currently in the development phase of my epubReader app. Utilizing CSS to customize the font style within UIWebView, however encountering a challenge with the fixed font size causing fluctuations in the number of pages when changing the font style. Seeki ...

Encountered a runtime error while trying to insert a list item <li> into a paragraph <p> element

Take a look at this code snippet: <%@ Page Title="Home Page" Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="WebApplication18._Default" %> <!DOCTYPE html> <html> <body> <p id="someId"></p& ...

Check the value of a single bit in JavaScript: Is the bit on (1) or off (0)?

Is there a way in JavaScript to determine if a single Bit is On (1) or Off (0)? function isBitOn(number, index) { // ... ? } // Example: let num = 13; // 1101 isBitOn(num, 0); // true 1 isBitOn(num, 1); // false 0 isBitOn(num, 2); // true 1 isBit ...