I have a array of objects which contain images and documents, I want to check is the mime_type is 'images/jpeg' or 'image/png' and then only display the first image in a tag. I am using react.
I tried this but I keep getting undefined
<img className={"img-fluid img-list"}
src={this.state.images.filter(img => (img.mime_type === 'image/jpeg' || img.mime_type === 'image/png') || {})[0].blob_url}
alt="" />
<img className={"img-fluid img-list"}
src={this.state.images.filter(img => (img.mime_type === 'image/jpeg' || img.mime_type === 'image/png'))[0].blob_url}
alt="" />
if check with a {} i dont get any links
any help much appriciated.
You have an error here:
this.state.images.filter(img => (img.mime_type === 'image/jpeg' || img.mime_type === 'image/png') || {})[0].blob_url
It should be:
((this.state.images.filter(img => (img.mime_type === 'image/jpeg' || img.mime_type === 'image/png')) || [])[0] || {}).blob_url
If you add a bit of indentation, it should be more clear where your error was:
(
(
this.state.images.filter(img => (
img.mime_type === 'image/jpeg' || img.mime_type === 'image/png'
)) // give me an array with only the images
|| [] // OR give me back an empty array if you cannot find any
)[0] // then give me the first element (image object) of the array
|| {} // OR give me back an empty object if the array is empty
).blob_url // finally give me the `blobl_url` of the object
Alternatively, you can use Array.prototype.find
, which will return the first item matching the criteria:
(this.state.images.find(img => (img.mime_type === 'image/jpeg' || img.mime_type === 'image/png')) || {}).blob_url
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.