Home > OS >  React | How to render only 1 object from an array that is part of a nested object
React | How to render only 1 object from an array that is part of a nested object

Time:12-30

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} />
 ))
}

CodePudding user response:

You could use 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/

CodePudding user response:

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}`]} /> }
  </>
)
  • Related