Working with Sample API
I'm workig with a sample RandomUser API. When running this code, it returns this object (see img #1). I'm attempting to retreive the data within 'results'. Creating a variable like
let result = data.result
returns (see img #2). But, when I try to log the gender, but calling console.log(result.gender)
, I get undefined.
How do I properly access the results data?6 Replies
results is an array, so even though it only has one entry, you have to treat it like an array
either you can set your
result
variable to data.results[0]
or you can console.log(result[0].gender)
So results is an array with 1 item, which contains an object with all the additional information?
yes
Ahh okay, that makes sense. It seems like a weird way to format things on the APIβs end
Thank you
Using an array with only one item is a common technique if you want to allow the possibility of having more than one item in the future. This avoids the need to rewrite the code. Only the data source needs to change.
Good to know, thank you