Working with Sample API

let api = "https://randomuser.me/api/";

function fetchData() {
fetch(api)
.then(response => response.json())
.then(data => {
console.log(data);
})
}

fetchData();
let api = "https://randomuser.me/api/";

function fetchData() {
fetch(api)
.then(response => response.json())
.then(data => {
console.log(data);
})
}

fetchData();
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?
No description
No description
6 Replies
Jochem
Jochemβ€’16mo ago
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)
Matt
MattOPβ€’16mo ago
So results is an array with 1 item, which contains an object with all the additional information?
Jochem
Jochemβ€’16mo ago
yes
Matt
MattOPβ€’16mo ago
Ahh okay, that makes sense. It seems like a weird way to format things on the API’s end Thank you
Chooβ™šπ•‚π•šπ•Ÿπ•˜
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.
Matt
MattOPβ€’16mo ago
Good to know, thank you
Want results from more Discord servers?
Add your server