Adrian Soleil Adrian Soleil - 1 year ago 104
React JSX Question

React Component iterate/loop properties of Mongo object

I do have a Mongo

that stores albums with predefined "slot" for its images and feel a bit stuck if there a way to loop over the properties of the collection in order to display images in separated divs.

I did used this code for mapping over the album covers and it worked great:

albums() {
return Albums.find().fetch();

{this.albums().map( (album) => {
return <div key={album._id}><img src={album.cover} /></div>

But now I ask you to help, is it possible to loop over photoOne, photoTwo, etc... and skip/don't display data if it is empty like in photoThree for example.

"_id" : "CHMHbNWWwZGaLGvB6",
"title" : "Text",
"cover" : "link",
"createdAt" : date,
"photoOne" : {
"titleOne" : "Text",
"coverOne" : "link"
"photoTwo" : {
"titleTwo" : "Text",
"coverTwo" : "link"
"photoThree" : {
"titleThree" : "",
"coverThree" : ""

Answer Source

I'm not a Mongo user, but in the map function you can check for the existing values, and handle it there. Something like (there is surely a cleaner way, though):

   this.albums().map( (album) => {
       for (key in album){
         if (key.startsWith('photo')){
           var title = Object.keys(album[key])[0];
           if (album[key][title].length != 0){
             console.log("Can use: " + Object.keys(album[key])[0])

Results in:

Can Use This: titleOne
Can Use This: titleTwo

Hope that helps, but it seems like having the photos with photoOne, photoTwo you are limiting the number of photos to use and requiring the need to use Object.keys to get the values out (without specifically using album.photoOne, album.photoTwo, etc.

If the album photos were stored in an embedded document, you could just include the photos and titles that existed and avoid having to check for empty ones. You would just loop through the photos that are present....if that makes sense.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download