Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Access most recent value in JSON nested object with JS

I’m trying to access the most recent element in the Time Series (5 min) object, without having to specify the date/time, after using this JS 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"];

So in this case (see screenshot) it’s Time Series (5 min) > 2022-04-21 20:00:00 -> 4. close, but I get an undefined error.

I even tried in the developer console with the full JSON file.
Using current_stock["Time Series (5 min)"] returns all of the child values in the console, but adding [0] or ["2022-04-21 20:00:00"] to the end throws an undefined error.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Raw JSON

>Solution :

You can access it like this:

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);

const timeSeries = current_stock['Time Series (5min)']
const key = Object.keys(timeSeries)[0]
console.log(timeSeries[key]['4. close'])
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading