I have the following API Data:
[ { "symbol": "AAPL", "name": "Apple Inc.", "price": 144.98, "changesPercentage": -1.22, "change": -1.79, "dayLow": 142.54, "dayHigh": 146.96, "yearHigh": 150, "yearLow": 93.7125, "marketCap": 2419368132608, "priceAvg50": 138.45343, "priceAvg200": 131.05212, "volume": 113982837, "avgVolume": 85057328, "exchange": "NASDAQ", "open": 144.81, "previousClose": 146.77, "eps": 4.449, "pe": 32.587097, "earningsAnnouncement": "2021-07-27T16:30:00.000+0000", "sharesOutstanding": 16687599204, "timestamp": 1627504655 } ]
And here is my code with a fake API code:
var $stocks = $('#stocks'); $.ajax({ type: 'GET', url: 'https://financialmodelingprep.com/api/v3/quote/AAPL?apikey=c0dabd2d8a382584d2144bdefde830f2', success: function (percent) { $.each(percent, function (i, item) { $stocks.append(percent.changesPercentage); }) } });
All I would like to do is get the changesPercentage and display it on my webpage with HTML and CSS. I will have various data from different companies, so a versatile solution would be very helpful.
Advertisement
Answer
You’re trying to get changesPercentage
from percent
, which is the entire response array. So that property would be undefined
.
Instead, it looks like you want to get that value from each element in the array. For that you would use the item
parameter of the callback function in $.each
:
$stocks.append(item.changesPercentage);
Alternatively, you could also use the i
parameter as an indexer for the original array:
$stocks.append(percent[i].changesPercentage);
As an aside, this appears to be a result of using poor variable names which confuse yourself. percent
is a misleading name for an array of objects. Something like results
would be better, or perhaps the plural form of whatever noun actually describes what these API results are.
Names are important in code. They carry information about what that thing is and how it can be used.