I have an object like this:
myObject: {
"artists" : {
"items" : [ {
"id" : "423587fgerhk34t",
"images" : [ {
"height" : 640,
"url" : "https://url",
"width" : 640
}, {
"height" : 320,
"url" : "https://url",
"width" : 320
}],
"name" : "Artist Name",
} ]
}
}
Excuse me for sounding stupid, but how do I, in my React app, reach the ID, images and name? Can someone ELI5 this for me?
I've tried
Object.entries(myObject).map()
Object.keys(myObject).map()
myObject.artists.items.map()
but none of them works, at least not what I'm trying.
(I cannot change the object, it's a response from an API)
Really appreciate some help here. I need to render images and artistname and save the ID.
Edit, been trying this for example:
const displaySearchResult = Object.keys(myObject).map((artist) =>
<div className="search-result-item">
<img src={artist.images[1].url} alt="Artist"/>
<b key={artist.id}>{artist.name}</b>
</div>
)
But basically, all I'm getting is
"Objects are not valid as a React child (found: object with keys {href, items, limit, next, offset, previous, total}). If you meant to render a collection of children, use an array instead." (Objects.entries)
or
"Cannot read properties of undefined ('reading items')" (myObject.artists.items.map())
CodePudding user response:
From the information you have given the only mistake you seem to be making is iterating over the keys of myObject
- which only has 1 key artists
and that clearly does not give what you're trying to do judging by the HTML you're trying to output.
In actual fact you need to use map
over myObject.artists.items
which is an array of objects with properties which seem to match what you're trying to output:
const displaySearchResult = myObject.artists.items.map((artist) =>
... rest of your code
);
CodePudding user response:
If you want to display 2 multiple image URL's dynamically for a single name, you can try with the below code.
const displaySearchResult = myObject.artists.items.map((artist) =>
<div className="search-result-item">
{artist.images.map((img) =>
<img src={img.url} alt="Artist"/>
)}
<b key={artist.id}>{artist.name}</b>
</div>
)
Or If you want to display one image with name and another image with same name dynamically, then you can try below code.
const displaySearchResult = myObject.artists.items.map((artist) =>
<div className="search-result-item">
{artist.images.map((img) =>
<div>
<img src={img.url} alt="Artist"/>
<b key={artist.id}>{artist.name}</b>
</div>
)}
</div>
)