Difficulties encountered when trying to load a URL or API that contains an array in javascript/p5js


I've run into a coding issue that I'm trying to troubleshoot in p5js.
My goal is to retrieve data from a URL/API. The line `kursMin[1]...` gives the correct stock value, but the line `kursMin[i]` returns `[object Object]2021-03-124. close`
Both lines seem similar to me, except for the lower one being more generic.
**Can anyone identify where the problem lies?** (I apologize for my simple explanation as I am new to p5js)
I've spent a lot of time searching for a solution without any luck. I have also experimented with different code combinations within the lower line, like `"" [] ''`, but nothing seems to work.
function kursMinus() {
  for (var i = 1; i < 7; i++) {
    kursMin[1] = dailyLong['Time Series (Daily)'][dateMin[1]]['4. close']; //works
    kursMin[i] = dailyLong['Time Series (Daily)'] + [dateMin[i]] + ['4. close']; //doesn't work
  }
}

I realized that the [] are necessary because of the space within the path.
In the preload function, I have initialized dailyLong as:

dailyLong = loadJSON("https://www.alphavantage.co/query?function=TIME_SERIES_DAILY&symbol=IBM&outputsize=full&apikey=demo");

I have declared the array as var kursMin = [];

Answer №1

One major issue you seem to be facing is the assumption that you're dealing with an Array when in fact, it's not.

The contents of dailyLong actually represent an object. The confusion arises due to the need to access keys within dailyLong using bracket notation [], given the presence of spaces (Time Series (Daily)) and special characters (2021-04-12). For more information on property accessors, you can refer here.

Based on your code, it seems like you have an array named dateMin containing the dates you wish to search through, which makes it the target for looping through to obtain daily closing prices (making it an actual array).

The purpose behind your second line isn't entirely clear; however, if your goal is simply to iterate over all the closing prices, then eliminate the + signs from the assignment (refer to the code snippet below).

Your first line is accurate because it accesses the object using bracket notation rather than dot notation. Just swap out the 1 with i. On the other hand, the second line is incorrect based on what you're attempting to achieve:

const dailyLong = {
  "Time Series (Daily)": {
    "2021-04-12": {
      "4. close": 123
    }
  }
}
// Correct, works:
dailyLong['Time Series (Daily)'][dateMin[1]]['4. close']

// Not incorrect, but not what you're trying to do:
dailyLong['Time Series (Daily)'] + [dateMin[i]] + ['4. close']

// First you get a reference to the object
const object = dailyLong['Time Series (Daily)'] // [object Object]
// Second you create a new array with 1 element, dailyMin[i] or '2021-04-12'
const array1 = [dailyMin[i]] // 2021-03-12
// Finally you create a second array with one element, '4. close'
const array2 = ['4. close'] // 4. close

object + array1 + array2 // [object Object]2021-03-124. close

Below is a code snippet demonstrating how you can traverse these values:

const dailyLong = {
  "Meta Data": {
      "1. Information": "Daily Prices (open, high, low, close) and Volumes",
      "2. Symbol": "IBM",
      "3. Last Refreshed": "2021-04-12",
      "4. Output Size": "Full size",
      "5. Time Zone": "US/Eastern"
  },
  "Time Series (Daily)": {
      "2021-04-12": {
          "1. open": "135.0200",
          "2. high": "135.3700",
          "3. low": "133.8500",
          "4. close": "134.5900",
          "5. volume": "3753959"
      },
      "2021-04-09": {
          "1. open": "134.8700",
          "2. high": "135.7400",
          "3. low": "134.7100",
          "4. close": "135.7300",
          "5. volume": "3023916"
      },
      "2021-04-08": {
          "1. open": "134.5700",
          "2. high": "135.6299",
          "3. low": "134.1600",
          "4. close": "135.1200",
          "5. volume": "4087228"
      },
      "2021-04-07": {
          "1. open": "133.8400",
          "2. high": "134.9400",
          "3. low": "133.7800",
          "4. close": "134.9300",
          "5. volume": "2976136"
      },
      "2021-04-06": {
          "1. open": "135.5800",
          "2. high": "135.6400",
          "3. low": "134.0900",
          "4. close": "134.2200",
          "5. volume": "3620964"
      },
    }
}

const dateMin = [
  '2021-04-12',
  '2021-04-09',
  '2021-04-08',
  '2021-04-07',
  '2021-04-06',
]

function kursMinus() {
  for (var i = 0; i < 5; i++) {
    console.log(dailyLong['Time Series (Daily)'][dateMin[1]]['4. close']); //works
    console.log(dailyLong['Time Series (Daily)'][dateMin[i]]['4. close']); //works
    // kursMin[i] = dailyLong['Time Series (Daily)'] + [dateMin[i]] + ['4. close']; //doesn't work
  }
}

kursMinus()

Answer №2

Many thanks for the detailed response you provided.
The concept behind the variable dateMin was to take monthly steps backwards in time. For example, if the most recent update was on 2021-04-12, then dateMin[i] would be set to 2021-03-12, 2021-02-12, and so forth.
I realize now that my mistake stemmed from misinterpreting the error message

dailyLong['Time Series (Daily)'][dateMin[i]] is undefined
. I had initially thought that the issue lied in the URL format being incorrect.
In reality, the error occurred because there was no available data entry for the date 2020-12-12, as it was not a trading day. This led me to understand that I need to devise a function that decrements the day by one until the last trading day with existing data is reached.

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

Retrieve the most recent information from a web scraper and display it on the Heroku application

After creating an API with Express.js and using cheeriojs to scrape a website, I deployed the API on Heroku. However, my web application is not fetching the latest data from the scraped website. It seems to be stuck showing old data. How can I make it co ...

AngularJS 1.7.x's ngRoute tabs navigation post authentication

In my current project, I am using ngRoute to route users to the login page and upon successful login, they should land on the dashboard page. However, I am facing a problem with the dashboard page where I need to have two or more tabs that render HTML pag ...

Learn how to retrieve URL parameters using HTML code

I would like to update the URL without refreshing the page as I am using an AJAX function to refresh a specific div. The issue I am encountering is that when the div is reloaded via AJAX, it does not recognize the URL parameter. Below is my code (I have a ...

What is the reason behind postgres' error message: "operator does not exist: json ? unknown

Trying to execute this specific query against my postgres database, I encountered a challenge: select distinct offer_id from offers where listing_id = 2299392 group by offer_id having not bool_or(status in ('Rejected', 'Draft&ap ...

Issue: ENOENT error occurred during execution on Docker Container due to missing file or directory '/root/.aws/credentials'

click here for image description While the app runs normally locally, attempting to run it in a Docker container results in an error displayed on the screen. This is my Docker file: FROM node:14.0.0 WORKDIR /app ARG DATABASE_URL ARG AWS_REGION ARG CLIENT_ ...

The only information returned from calling mongoose's Model.save() method are the fields { _id, __

I've encountered a problem even though I believe I'm following all the right steps. I'm attempting to save an item from a form into my mongodb collection using mongoose. This is what my schema looks like: // stationmodel.js export const Sta ...

Exploring MongoDB querying with two keys in conjunction with Express JS and NodeJS

I'm seeking assistance with my web application developed using Express JS and Node. I am encountering issues with the .find() command when trying to search for multiple words. It's interesting because using the $all command works when two words ...

Unpacking a JSON object with nested objects

Having an issue with deserializing a JSON string using Newtonsoft.Json library. The deserialized object keeps returning null, possibly due to the address object within the player object. Here is the JSON string: { "player":{ "id":"ed704e61-f ...

Retrieve the information stored in MongoDB and then store it back into MongoDB

I'm completely new to mongoDB. I'm currently developing an application that includes a search button. This button searches the mongoDB for a specific value, and if found, it returns JSON data. If not found, users have the option to add it to the ...

Enhancing Typography in Material UI with Custom Breakpoints in React CustomThemes

Currently, I am utilizing material UI and React to develop a single-page application (SPA). However, I have encountered an issue with ensuring that my pages are responsive for smaller screen sizes. To address this, I have been manually adding fontSize: { x ...

obtain the string representation of the decimal HTML entity value

Similar Question: how to create iphone apps similar to ibeer, imilk, ibug, ibeer Using javascript to obtain raw html code Imagine having an html section like this: <div id="post_content"> <span>&#9654;<span> </div> ...

What is the best way to retrieve data from multi-dimensional JSON structures?

Looking to extract specific values from my JSON file. console.log( objects.assignments.header.report_type ); I need to display HOMEWORK Javascript $.ajax({ url: "/BIM/rest/report/assignment", type: "POST", dataTyp ...

`Inability to remove item from array in Vue.js`

I've been struggling to understand why this feature isn't functioning as expected. I'm using sample code for reference, but it's not behaving the same way. When I click on the delete button, nothing happens even though it should remove ...

I am puzzled as to why my text and div boxes are displaying in my navbar/hamburger menu instead of at the bottom of the page

Greetings, everyone! This is my debut post here so bear with me if it's not presented in the correct format. Currently, I am deep into creating a website using HTML, CSS, and just a hint of JavaScript. My primary focus right now is on building the ho ...

What is the best way to determine the nearest pixel point indexes of an RGB list compared to another RGB list?

I have been working on an Image Processing Task and I have outlined all the details below. What I aim to accomplish: In this task, I am dealing with two lists: colorlist = approximately 500 RGB values (extracted from Picture 1) color = around 1200 or m ...

Outer div encapsulating inner div within its boundaries

I am looking for a solution where the inner div stays fully contained within the outer div, without overflowing and overlapping with the padding of the outer div. Here is a code sample that demonstrates the issue .inner { /* Overflow */ overflow-wra ...

Utilizing jQuery BBQ for Seamless Transitions – From Fading to Sliding and More

This is my first time posting a question here, even though I am an active user of stackoverflow. I have developed a website using jQuery BBQ to load pages through AJAX while still maintaining the ability to track history with the back button and other fun ...

Tips on sorting a struct array with qsort

Tasked with the challenge of retrieving a binary file, reading it into an array comprised of structs and sorting it based on a specific array within each struct has proven to be quite the hurdle. At this moment in time, my main struggle lies within the rea ...

Having trouble setting a value in a Vue.js variable

Upon assigning a value retrieved from the firebase collection, I encountered the following error message. Error getting document: TypeError: Cannot set property 'email' of undefined at eval (Profile.vue?5a88:68) Here is the code snippet in que ...

Utilizing Node.js in Phonegap

Currently, I am in the process of creating an iOS application with PhoneGap and I have an interest in incorporating node.js into a specific aspect of it. Is it possible to integrate an instance of node.js within the app using PhoneGap? ...