How to retrieve the latest value from a nested object using JavaScript in JSON

I am attempting to access the most recent element in the Time Series (5 min) object without specifying the date/time after running this JavaScript code:

var getStock = new XMLHttpRequest();
getStock.open("GET","https://www.alphavantage.co/query?function=TIME_SERIES_INTRADAY&symbol=IBM&interval=5min&apikey=demo", false);
getStock.send(null);

var current_stock = JSON.parse(getStock.responseText);
console.log(current_stock);
var current_stock_price = current_stock["Time Series (5min)"][0]["4. close"];

In this instance (refer to screenshot), I am looking at Time Series (5 min) > 2022-04-21 20:00:00 -> 4. close, but I am encountering an undefined error.

Even when trying it in the developer console with the complete JSON file, using

current_stock["Time Series (5 min)"]
displays all child values in the console. However, appending [0] or
["2022-04-21 20:00:00"]
at the end results in an undefined error.

https://i.sstatic.net/DRVVn.png

Answer №1

To retrieve the information, simply follow these steps:

let fetchStock = new XMLHttpRequest();
fetchStock.open("GET", "https://www.alphavantage.co/query?function=TIME_SERIES_INTRADAY&symbol=IBM&interval=5min&apikey=demo", false);
fetchStock.send(null);
let stockData = JSON.parse(fetchStock.responseText);

const timeSeries = stockData['Time Series (5min)'];
const key = Object.keys(timeSeries)[0];
console.log(timeSeries[key]['4. close']);

Answer №2

The reason for the unavailability of the 0 index in current_stock["Time Series (5min)"] is because it is an object, not an array. If you wish to retrieve the first item from current_stock["Time Series (5min)"], you can follow these steps:

var getStockData = new XMLHttpRequest();
getStockData.open("GET","https://www.alphavantage.co/query?function=TIME_SERIES_INTRADAY&symbol=IBM&interval=5min&apikey=demo", false);
getStockData.send(null);

var current_stock = JSON.parse(getStockData.responseText);
console.log(current_stock);
var keysList = Object.keys(current_stock["Time Series (5min)"]); // retrieve all keys in current_stock["Time Series (5min)"] object
console.log(keysList); // keysList is an array, so you can access the first item as keysList[0]
var current_stock_price = current_stock["Time Series (5min)"][keysList[0]]["4. close"];

Answer №3

Following your suggestion to change [0] to ["2022-04-21 20:00:00"], the code functions perfectly. The revised code snippet is as follows:

var getStock = new XMLHttpRequest();
getStock.open("GET","https://www.alphavantage.co/query?function=TIME_SERIES_INTRADAY&symbol=IBM&interval=5min&apikey=demo", false);
getStock.send(null);

var current_stock = JSON.parse(getStock.responseText);
var current_stock_price = current_stock["Time Series (5min)"]["2022-04-21 20:00:00"]["4. close"];
console.log(current_stock_price)

If you prefer not to use keys, you can utilize Object.values() to retrieve the data:

var getStock = new XMLHttpRequest();
getStock.open("GET","https://www.alphavantage.co/query?function=TIME_SERIES_INTRADAY&symbol=IBM&interval=5min&apikey=demo", false);
getStock.send(null);

var current_stock = JSON.parse(getStock.responseText);
var current_stock_price = Object.values(current_stock["Time Series (5min)"])[0]["4. close"];
console.log(current_stock_price)

This approach will fetch the most recent entry.

Answer №4

The issue arises from attempting to treat an object like an array.

current_stock["Time Series (5min)"]["2022-04-21 20:00:00"]["4. close"]
is the proper way to access the desired value in your code example.

To address your question about looping through this structure, you will need to convert the object into an array.

An effective method is utilizing Object.entries(), as shown below:

stock_date_prices = Object.entries(current_stock['Time Series (5min)'])

for (const [datetime, prices] in stock_date_prices) {
  console.log("The closing price at %s was %s", datetime, prices['4. close'])
}

If you require a more comprehensive explanation on looping through JavaScript objects, please refer to this advise on Stack Overflow.

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

Is it possible to limit the values of parameters with react-router?

Currently, I am in the process of developing a website using react and react-router. I have two different types of routes set up, as shown below: <Route name="products" path="/:type/*" handler={ ProductList } /> <Route name="generic-template" p ...

Unlimited scrolling feature on a pre-filled div container

Looking for a way to implement infinite scroll on a div with a large amount of data but struggling to find the right solution? I've tried various jQuery scripts like JScroll, MetaFizzy Infinite Scroll, and more that I found through Google search. Whi ...

Struggling to retrieve a class within an <a> element in jsTree when hovering?

I'm currently utilizing jsTree and below is how I'm initializing it... function setupJSTree(data){ $("#treeSelector").jstree({ "plugins" : ["themes","json_data","UI","types"], "themes" : { "theme":"def ...

Tips for executing an asynchronous fetch prior to the first rendering

Currently, I am working with the Wordpress API using Next.js on the front end. My goal is to fetch my navigation/menu data and have it pre-rendered. However, my attempts have only resulted in an empty <nav> </nav> element being rendered when I ...

What is the method for calculating the difference in days between two Jalali dates when selecting the second date picker input?

I have integrated the Persian Datepicker script from GitHub to display jalali dates on my webpage. Users can select date1 and date2 from the datepicker to input their desired dates. Below is the code snippet: $(document).ready(function() { $('. ...

The $watch function is triggered even when the expression remains unchanged

Within my controller, I have a variable named datetime that gets updated by a timer every second. What I need to accomplish is some work when the day changes. To achieve this, I set up the following watcher: $scope.$watch("datetime | date: 'MM/dd/yyy ...

The information does not display in the AngularJS-generated table

Struggling with AngularJS directives? Let's take a look at the code: <div ng-controller="Controller"> <table> <thead> ....... </thead> <tfoot> ....... </tfoot> <tbody> < ...

Encountered an issue while trying to retrieve a value from an object within a

Reviewing the following JSON response: [ {"name": "Afghanistan", ...}, {"name": "country 2" ,...}, {"name": "country 3" ,...}, ] My goal is to extract only country names from t ...

Basic $http.get request including parameters

I've been attempting to send an HTTP request using the AngularJS $http service like this: $http.get('http://myserver:8080/login?', { params: {username: "John", password: "Doe" }, headers: {'Authorization': ...

Integrating Gesture Handling in Leaflet JS for two-finger scrolling enforcement

Have you ever noticed that when you're using a mobile device and scrolling down a webpage with a Google map, the map goes dark and prompts you to "Use two fingers to move the map"? https://i.stack.imgur.com/4HD1M.jpg I am interested in incorporating ...

Using the Protractor tool to close a window popup

this.compareProductTitles = async function(title) { await browser.getAllWindowHandles().then(function (handles) { handles.forEach(function (handle) { console.log(handle.toString()); browser.switchTo.window(handle); ...

In the callback function within Array.prototype.map, make sure to access the newly created array

Array.prototype.map() creates a new array. How can I use this new array within the callback function passed to Array.prototype.map()? For instance: someArray.map(function(item, idx, arr) { return { theCreatedArray: xyz }; }); What should I assign to ...

Change the selection box to a checkbox

I am struggling to retrieve the value of a selection box inside jQuery. Specifically, I need to access the selection box value within a function that triggers on a checkbox change event: This is what I have so far: $('input').on('change& ...

Retrieving data from controllers and passing it to directives in Angular applications

I have integrated a directive into my Angular website to generate a customized page header. Within this header, I aim to display the user's first and last name. My application is enclosed within a MainController. Below is the rendered HTML: <html ...

List out IP addresses in JavaScript

Is it possible to allow users to input a range of IP addresses in a specific format? 10.5.15.[22-25],10.5.16.[35-37],10.5.17.20 The desired outcome is to return an array of these IP addresses for connection checking purposes later on. 10.5.15.22 10.5.15 ...

The initial render in a Kanban board seems to be causing issues with the functionality of react-beautiful-dnd

I recently integrated a Kanban board into my Next.js and TypeScript project. While everything seemed to be working fine, I encountered a minor glitch during the initial rendering. Interestingly, when I refreshed the page, the drag and drop functionality st ...

How to implement file uploading with Node.js and Angular using the formidable module

I am having trouble uploading files with angular and nodejs using formidable. I can't seem to post anything to the server, despite trying the following code: server var form = new formidable.IncomingForm(); form.uploadDir = path.join(__dirn ...

Determine if an Android application has been installed using JavaScript or jQuery

I'm working on an Android app that is also accessible via a web browser. I want to add a banner prompting users to install the Android application if they haven't already. How can I use JavaScript or jQuery to detect if the user has the app insta ...

Warning: HTML input values are being cleared when added

I've been working on some code that adds an input field when a button is clicked. When the limit reaches 5 (counter), it displays a bootstrap warning. The issue I'm facing is that after hitting "add field" more than 5 times, the values in the fie ...

What is the best way to incorporate multiple list views within a single list view?

I am currently developing a Flutter app that will display feeds. Specifically, I want to have the first list (horizontal) show 4 workouts, the second list (vertical) show 4 posts, the third list (horizontal) show 4 coaches, and the fourth list show 4 posts ...