0

I have this data structure:

const data = [
 {
   title: 'title',
   description: 'description'
   images: [
    { mainImg: 'url' },
    { img1: 'url' },
    { img2: 'url' },
    { img3: 'url' },
  ],
 },
 ...
]

My question is, how can I render only the mainImg separated from the others? And how can I render the other images without the mainImg.

What I've tied so far is to map through the images like this: (I did mapped through data before)

{data.images.map((img, index) => (
  <img
    key={`image${index}`}
    src={img.mainImg}
    className={styles.mainImg}
  />
 ))
}

This worked, but the issue is that I map through all the images and when I open the consoles, all the images are rendered but they are not visible because they don't have the src tag. (I think).

Simply trying to use data.images.mainImg as the src value doesn't render anything, and also does not throw any errors.

Also, I have an issue trying to render all the other images except the mainImg. This is what I've tried but I get lost and I don't know what the src value should be.

{data.images
  .filter((img) => img.mainImg != project.images.mainImg)
  .map((img, index) => (
    <img src={img} />
 ))
}

2 Answers 2

1

You could use hasOwnProperty : https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/hasOwnProperty

data.images.map((e, i) => {
  if (e.hasOwnProperty('mainImg')) {
    // Do something with mainImg
  }
  //Do something with the others
})

A JSfiddle with example : https://jsfiddle.net/RyanZee/hu189jxd/12/

Sign up to request clarification or add additional context in comments.

Comments

0

Do you always have a mainImg at index 0? If so you can use

const [firstImg, ...imgs] = data.images;
return (
  <>
    <img src={firstImg.mainImg} ... />
    { imgs.map((img, index) => <img src={img[`img${index + 1}`]} /> }
  </>
)

1 Comment

It won't be always at the same index

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.