Skip to content
Advertisement

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.

Raw JSON

Advertisement

Answer

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'])
Advertisement