I am trying to access varaibles in the object returned by an API but it's inside of another object "0" in this case
Screenshot of console enter image description here
JavaScript code
fetch('https://dad-jokes.p.rapidapi.com/random/joke', options)
.then(response => response.json())
.then(response => {
console.log(response)
document.getElementById("joke").innerText = (response.body)
})
.catch(err => console.error(err));
I can't write console.log(response.0.setup) and console.log(response.body.0.punchline) because JavaScript won't let me. How would i access the setup and punchline from JS?
CodePudding user response:
I don't have an API key to test this out myself, but it sounds like you can solve this with bracket notation. Any object property can be accessed like object['property']
which is equivalent to the dot notation object.property
for properties with string names. In this case your property is named with a number so the bracket notation is the only way to access it.
This should achieve what you're trying to do
document.getElementById("joke").innerText = (response[0])
and you can chain off of that to access the setup and punchline like
const punchline = response[0].punchline