When inconsistencies are encountered when filling an array with JSON data, an empty array will be displayed in the console.
P粉438918323
P粉438918323 2023-08-03 11:50:47
0
1
452
<p>I'm trying to get some data using the AlphaVantage API, and I want to store all the dividends paid by a certain stock in an array. I'm just trying to save dividends now, but in the future I'd like to be able to associate dividends with specific dates. <br /><br />Functions for retrieving data:</p><p><strong></strong></p> <pre class="brush:php;toolbar:false;">async function fetchTimeSeriesDailyAdjusted (ticker) { //Fetch function to get the daily close and the dividends const apiTimeSeriesDailyAdjusted = `https://www.alphavantage.co/query?function=TIME_SERIES_DAILY_ADJUSTED&symbol=${symbol}&apikey=${apiKey}`; //Lik of the API - update the symbol try { const response = await fetch(apiTimeSeriesDailyAdjusted); const data = await response.json(); const historicalDividend = []; //Array of the dividends for (let date in data['Time Series (Daily)']) { //This for should make the code go through all the JSON historicalDividend = entry ['7. dividend amount']; //This should store the dividend while the for loop "goes" } console.log(historicalDividend); //Console log to see the dividend return historicalDividend; //Value that the function must return } catch (error) { console.error('Error fetching apiTimeSeriesDailyAdjusted'); //Log of the error } }</pre> <p>This is the function I created, but as I can see, and probably you can see too, it doesn't work. </p>
P粉438918323
P粉438918323

reply all(1)
P粉739942405

The problem is that you declare a variable called historicalDividend, initialize it to an empty array, and then reassign the entire variable to the time series data on each iteration, which means you overwrite the value each time. Also, entry is undefined, I think you might want to use date.

To solve all these problems, you should use the map() method, which accepts an array, loops over it, and creates a new array using the callback function return value.

As another tip: You should check the response's HTTP status code to make sure you're getting the expected response.

Here is a version of your code that fixes both issues:


async function fetchTimeSeriesDailyAdjusted(ticker) {
  //Fetch function to get the daily close and the dividends
  const apiTimeSeriesDailyAdjusted = `https://www.alphavantage.co/query?function=TIME_SERIES_DAILY_ADJUSTED&symbol=${symbol}&apikey=${apiKey}`; //Lik of the API - update the symbol

  try {
    const response = await fetch(apiTimeSeriesDailyAdjusted);
    // Check for HTTP response code
    if (!response.ok) {
      throw new Error(
        $`Fetching daily time series data failed with status code '${response.status}'`
      );
    }
    const data = await response.json();
    const historicalDividend = data["Time Series (Daily)"].map(
      (entry) => entry["7. dividend amount"]
    );

    console.log(historicalDividend); //Console log to see the dividend

    return historicalDividend; //Value that the function must return
  } catch (error) {
    console.error("Error fetching apiTimeSeriesDailyAdjusted"); //Log of the error
  }
} 
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!