I am trying to console.log some JSON values from an OpeanSea api call payload. I can successfully hit the end point as seen in the console when I run this:
await fetch(`https://api.opensea.io/api/v1/collections?asset_owner=${currentAccount}&offset=0&limit=300`, options)
.then(response => response.json())
.then(response => console.log("collection owned by current address", response))
but when I try to log only one attribute from the response object:
await fetch(`https://api.opensea.io/api/v1/collections?asset_owner=${currentAccount}&offset=0&limit=300`, options)
.then(response => response.json())
.then(({ assetts }) => {
assetts.forEach((attributes) => {
console.log(attributes.name)
})
})
I see
TypeError: Cannot read properties of undefined (reading 'forEach')
Is
assetts
an arbitrary name to iterate through? I think this is what i dont understand
You should know the structure of json and target the required attributes. Like in your case its collections array which is array of object and each object contains name key so you can target key like:
await fetch(`https://api.opensea.io/api/v1/collections?asset_owner=${currentAccount}&offset=0&limit=300`, options)
.then((response) => {
return response.json();
})
.then((assetts) => {
assetts.collections.forEach((attributes) => {
console.log(attributes.name);
});
})
.catch((error) => {
console.log({ error });
});
In your first then block you should have to return response after parsing it, if you want to use the parsed data in next then block.
Tip: It is a good practice if you also handle error by putting catch block after then block.