10

I want to render nested array elements. To render elements I used .map but it is not working for second array.

Using list=[{value: 'One', list:[{value: 'abc', selected: false}, {value: 'efg', selected: false}]}, {value: 'Two', list: [{value: 'psr', selected: false}]}];

   list.map((item, index) => {
        return (
          <div key={index}>
            <ul >{item.value}</ul>
            item.list.map((subitem, i) => {
              return (
                 <ul >{subitem.value}</ul>
              )
            })
          </div>
        )
      })

Am I missing anything here?

Thanks

6
  • Do you want to render them in nested lists, or flatten the array? Commented May 3, 2017 at 9:36
  • @TomFenech I have to show nested array details Commented May 3, 2017 at 9:37
  • I can see your array, what you need to show us is the desired structure of the HTML that you are trying to produce. At the moment, what you have is invalid. Commented May 3, 2017 at 10:06
  • @TomFenech yes. I don't know how to use .map for nested array Commented May 3, 2017 at 10:11
  • jsfiddle.net/jwm6k66c/2611 Check this. Commented May 3, 2017 at 10:17

1 Answer 1

31

Try this. You missed { } before your second map

 list.map((item, index) => {
            return (
              <div key={index}>
                <ul >{item.value}</ul>
               {
                item.list.map((subitem, i) => {
                  return (
                     <ul ><li>{subitem.value}</li></ul>
                  )
                })
               }
              </div>
            )
          }

DEMO: https://jsfiddle.net/jwm6k66c/2611/

Sign up to request clarification or add additional context in comments.

9 Comments

Try adding an explanation to your answer!
@TomFenech I was in middle of adding
Your answer deals with a possible syntax error but fails to take into account the fact that a text node is not a permitted child of a <ul> element.
Throws error. It says Cannot read property 'map' of undefined. Referd item.list.map
Okat. Thanks @Ved
|

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.