0

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.

2 Answers 2

1

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>
      </>
    )
  }
 </>
 )
}
Sign up to request clarification or add additional context in comments.

1 Comment

This is very useful. However, after I deleted one image array, making it blank like this-- itemb: [''], it produces an error. But if not, your code works flawlessly. Thanks.
0

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.

5 Comments

One more question. I'm new to Reactjs and basically know a thing or two now. In your code, what does this mean -- "item.itemb && arr.itemb.length > 0 &&". Thanks.
@DaveMoreno Oops! It was a typo. I updated my answer. Thanks.
Okay, but what does this line means if I'm gonna use it for future references? Really appreciate it. Thanks.
@DaveMoreno It's a kind of validation, in my codes it only renders image array only when it has valid values like your sample data. when there is no itemb or there's no items in itemb, there's no need to render them. :D And If I didn't validate itemb then it will occur a bug when callding item.itemb.map() function. It is recommended to validate before rendering.
Thanks. Great help.

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.