DaOneRom
DaOneRom

Reputation: 294

A map within a map from an array, within an array

ReactJS Newbie here. Basically, I have an array. Then another array within it. Please see below:

arr = [{
   itema: 'a',
   itemb: ['img/image1.jpg', 'img/image2.jpg']
}, {
   itema: 'b',
   itemb: ['img/image3.jpg', 'img/image4.jpg', 'img/image5.jpg']
}, {
   itema: 'c',
   itemb: ['img/image6.jpg', 'img/image7.jpg']
}
]

I've successfully mapped the array above, like this:

arr.map((arr, i) => {
   return(<span>{arr.itema}</span>)
})

But my problem is the inner-map. Is it possible to map this array within the given array? Thanks in advance.

Upvotes: 0

Views: 54

Answers (2)

Diamond
Diamond

Reputation: 3428

Of course you can.

arr.map((item, i) => {
   return (
     <div>
         <span>{item.itema}</span>
         {
            item.itemb && item.itemb.length > 0 &&
            item.itemb.map(image => (<img src={image} />))
         }
     </div>
    );
})

This will rendered like below (for only one item in arr)

  <div>
   <span>a</span>
   <img src="img/image1.jpg" />
   <img src="img/image2.jpg" />
  </div>

And I noticed that you used same item name arr as parent array arr in first map function. I recommend to use different key name to identify correctly.

Upvotes: 0

haMzox
haMzox

Reputation: 2109

Yes, ofcourse it is possible to show nested arrays in React or any other framework.
For e.g. in your render function

render() {
 return (
 <>
  {
   arr.map((arr, i) =>(
      <> 
       <span>{arr.itema}</span>
       <span>{arr.itemb.map(item => (<span>{item}</span>))}</span>
      </>
    )
  }
 </>
 )
}

Upvotes: 1

Related Questions