-8

I am running a function which returns json data:

const stocks = await response.json();
let stocksData = stocks.values;

If I print out the result gives a result as:

0 :  {datetime: '2023-01-18', open: '1.07940', high: '1.08870', low: '1.07670', close: '1.07970'}
1 :  {datetime: '2023-01-19', open: '1.07945', high: '1.08365', low: '1.07820', close: '1.08300'} 
2 :  {datetime: '2023-01-20', open: '1.08300', high: '1.08585', low: '1.08020', close: '1.08530'} 
3 :  {datetime: '2023-01-23', open: '1.08595', high: '1.09270', low: '1.0

I am trying to get values as: open, high, low, close with below line of code:

var open = stocksData["open"];

and print:

console.log("Open: " + open);

I get result:

Open: undefined

I thought its because stocksData is an object and tried to change it to a string and try to access the value again as follows:

var b = JSON.parse(JSON.stringify(stocksData)); 
var high = b["high"];
console.log("High: " + high);

I still get:

High: undefined

And there where I am stuck now, where am I getting it wrong?

Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335
Exsent
  • 25
  • 6
  • 3
    You can't completely ignore the fact you have **multiple** objects (0, 1, 2, 3) and try to treat `stocks.values` as a *single* object. – Quentin Feb 28 '23 at 11:44

1 Answers1

-1

It seems that stocks.values is an array, so you can use something like

var open = stocksData[0]["open"];

Or, you can loop through the array with an for-loop of some kind

Edit:

for (entry of stocksData) {
  console.log('Open: ' + entry.open)
  console.log('High: ' + entry.high)
  console.log('Low: ' + entry.low)
  console.log('Close: ' + entry.close)
}

See here for all documentation regarding arrays and looping

dijkdev
  • 59
  • 6