-3

In a React project, I'm calling data from JSON data as: enter image description here

In short JSON data is as:

const listData =  [
{
"_id":"abscdf456",
"bucket": {code: "videos"}
"contents": [
{}, {}, {}, {}
]
},
{
"_id":"absusi789",
"bucket": {code: "videos"}
"contents": [
{}, {}, {}, {}, {}, {}
]
},
{
"_id":"abssth7890",
"bucket": {code: "photos"}
"contents": [
{}, {}, {}, {},{}, {},{}, {}, {}
]
},
{
"_id":"yuiaf456",
"bucket": {code: "videos"}
"contents": [
{}, {}, {}
]
}
]

I have tried in the following way

listData.map((data) => (
<div>
{
data.bucket.code == "videos" ? 
({/* Map only videos contents object */}) : ({/* Map only photos contents object */})
}
</div>
))

Another trial I did is const videoData = listData.filter(data => data.bucket.code === "videos") but, no use as It got repeated many times

So basically My intention is to map the 'contents object' of each bucket non-repeated. What could be the best possible solution?

Pranav
  • 1,487
  • 2
  • 25
  • 53

2 Answers2

0

I believe you need to map the array with forEach or using the filter to not repeat yourself as you want.

I put a list to show item by item <ul> <li>

  • content 1
  • content 2
  • content 3
listData.map((data) => (
    <div key={data._id)}>
       {data.bucket.code === 'videos' && (
          <ul>
            {data.contents.forEach((content) => {
              <li key={content.somethingToKey}>{content}</li>
            })}
          </ul>
       )}
       {data.bucket.code === 'photos' && ({/* Map only photos contents object */})}          
    </div>
));
Remato
  • 93
  • 9
0

Expanding on the way you tried it:

const renderVideo = (video) => (<div>{video.name}</div>);
const renderPhoto = (photo) => (<div>{photo.name}</div>);

listData.map((data) => (
<div>
{
  data.bucket.code == "videos" ? 
    data.contents.map(video => renderVideo(video)) : 
    data.contents.map(photo => renderPhoto(photo))
}
</div>
));
James
  • 20,957
  • 5
  • 26
  • 41