Search code examples
javascriptarraysvue.jsobjectstrapi

if condition inside map or push or something else


as i am new in js, i need your help becuase i cant find any help anywhere else.

i have this array matchingAlbums

[
   {
      "id":6,
      "title":"Album1",
      "slug":"album1",
      "media":[
         {
            "id":156,
            "name":"image1.jpg",
            "width":2048,
            "height":2048,
            "hash":"image1_d556c8283b",
            "ext":".jpg",
            "mime":"image/jpeg",
            "size":273.98,
            "url":"/uploads/image1_d556c8283b.jpg",
         },
         {
            "id":157,
            "name":"video1.mp4",
            "width":640,
            "height":1202,
            "formats":{
               "thumbnail":{
                  "ext":".png",
                  "mime":"image/png",
                  "width":83,
                  "height":156,
                  "size":31.45,
                  "url":"/uploads/thumbnail_video1.png"
               },
               "large":{
                  "ext":".png",
                  "mime":"image/png",
                  "width":532,
                  "height":1000,
                  "size":647.84,
                  "url":"/uploads/large_video1.png"
               },
               "medium":{
                  "ext":".png",
                  "mime":"image/png",
                  "width":399,
                  "height":750,
                  "size":430.94,
                  "url":"/uploads/medium_video1.png"
               },
               "small":{
                  "ext":".png",
                  "mime":"image/png",
                  "width":266,
                  "height":500,
                  "size":230.47,
                  "url":"/uploads/small_video1.png"
               }
            },
            "ext":".mp4",
            "mime":"video/mp4",
            "url":"/uploads/video1.mp4",
         }
      ]
   }
]

some are images and some are videos

without videos this code works fine

async fetch() {
  const matchingAlbums = await this.$strapi.find('albums', {
    slug: this.$route.params.slug,
  })
  const images = []
  matchingAlbums[0].media.map((item) => {
    return images.push({
      thumb: `if mp4 then item.formats.large.url else item.url`
      width: item.width,
      height: item.height,
      src: item.url,
      mime: item.mime,
    })
  })

  this.album = matchingAlbums[0]
  this.images = images
},

but now that i have videos in my array, i need to change the thumb to the image path from item.formats.large.url where the mime is video/mp4

I tried doing if statement inside the map and push but it wont work. I appreciate your help.


Solution

  • Use a ternary expression.

    thumb: item.mime == 'video/mp4' ? item.formats.large.url : item.url,