0

How do i dynamically display an array that has multiple arrays. The nested arrays have multiple objects.

e.g.

Var obj = 
[
  [
    {
      name: "Test 1",
      category: "Test 1"
    }, 

    {
      name: "Test 2",
      category: "Test 1"
    }, 
  ],

  [
    {
      name: "Test 1",
      category: "Test 2"
    }, 

    {
      name: "Test 2",
      category: "Test 2"
    }, 
  ]
]

So how do i dynamically display this and render it in a react component I tried [below] and it works perfect and displays the first array-object, but i cant figure out a way to make it display the rest

list = obj[0].map((e, index) => {  
   return (
      <div key={index}>
         <p>{e.name}</p>
         <h6>{e.category}</h6>
      </div>
   )
})      
return (
   <div>
      {list}             
   </div>
)

1 Answer 1

1

You have a couple of options here.

One is to explicitly loop over the outer array and then the inner arrays:

const list = obj.map(cat => cat.map((e, index) => {  
   return (
      <div key={index}>
         <p>{e.name}</p>
         <h6>{e.category}</h6>
      </div>
   )
}));      

The problem here is that index will not be unique on the page. As a general rule, you should not be using an array index as a component key anyway. You'd be better off using something like

   (
      <div key={`${e.name}-${e.category}`}>
         <p>{e.name}</p>
         <h6>{e.category}</h6>
      </div>
   )

Another approach would be to flatten the array:

const list = [].concat(...obj).map(e => (
  <div key={`${e.name}-${e.category}`}>
    <p>{e.name}</p>
    <h6>{e.category}</h6>
  </div>
);
Sign up to request clarification or add additional context in comments.

7 Comments

I think the correct way would be a recursive function.
@Vencovsky there's no "correct way" here. It's a matter of preference and there's nothing wrong with simple loops or flattening.
@EmileBergeron, sorry. I think that a recursive function would be a better way if the object can have more than 2 levels of nested arrays.
@Vencovsky sounds like the beginning of a good answer :) That said, since the OP is struggling with nested arrays, I'd guess they might struggle with recursion (no disrespect intended to OP... we all have to start somewhere!)
@Vencovsky in that case, it would be a good point since it would invalidate flattening and simple loops anyway ;)
|

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.