Ad

How To Access The Img Value? Javascript

I have an array of objects with several properties, one of them is called 'file', of which there are two types as represented below

const products = [
  {
    functional_id: "2_recharges",
    quantity: 1,
    title: "Coffret empreinte rouge",
    file: "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAZAA…em3dIEUUE1O4fn/M8l6v+f6VPgptdk2plAAAAAElFTkSuQmCC"
  },
  {
    functional_id: "sacs_blancs",
    quantity: 1,
    title: "Sacs blancs",
    file: "data:image/;base64,"
  }
]

It's the first time I work with image files and I don't know how to differentiate to create a condition so that only those containing the word 'png' in its value are displayed, in the case of the example the first one, since those that are like the second one don't display any image

I tried to treat them as a string to check if they contained the value string but it doesn't work, as I understand that they are not strings.

If someone can give me an idea of how to create my condition. Thank you very much in advance

Ad

Answer

You will want to use the js filter method to check whether the file includes 'png'.

const products = [{
    functional_id: "2_recharges",
    quantity: 1,
    title: "Coffret empreinte rouge",
    file: "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAZAA…em3dIEUUE1O4fn/M8l6v+f6VPgptdk2plAAAAAElFTkSuQmCC"
  },
  {
    functional_id: "sacs_blancs",
    quantity: 1,
    title: "Sacs blancs",
    file: "data:image/;base64,"
  }
]

const pngImages = products.filter(product => product.file.includes('png'))
console.log(pngImages)

Ad
source: stackoverflow.com
Ad