1

I am new to react and I am having trouble finding a way to map an array within an array to display the username and id in the component. How can I achieve this? Is this a wrong approach?

[Array(4)]
        0: Array(4)
            0: {user: "testuser1", id: "2"}
            1: {user: "testuser2", id: "3"}
            2: {user: "testuser3", id: "4"}
            3: {user: "testuser4", id: "5"}
    length: 4
    __proto__: Array(0)
    length: 1
    __proto__: Array(0)

Thanks

3
  • Have you read the documentation Lists and Keys? It will explain how to map your data to components, which you can then render. Commented Mar 14, 2021 at 11:31
  • Hi, I am able map normal arrays without any problem, but here I'm finding it difficult to get it work. userinfo is the state which holds this array. userinfo.0 throws an error. Commented Mar 14, 2021 at 11:35
  • 1
    It is the same idea, you'll just need one map to map the contents of the outer array, and then another to map the contents of the inner array arr.map(inner => inner.map(obj => <p key={obj.id}>{obj.user}</p>));. To access an element in an array, you could use userInfo[0], but it's unclear whether your (outer) array can have more than one nested array. Using two maps will take care of both cases (0 or more nested arrays) Commented Mar 14, 2021 at 11:38

1 Answer 1

2

prehistoricbeast - try this:

  return(
    <div>
      {Object.keys(data).map((key) => {
         return (
           <div key={key}>
              <h1>{key}</h1>
              {data[key].map((dataItem) => {
                return (
                 <span key={dataItem.user}>{dataItem.id}</span>
                )
               })}
           </div>
         )
       })}
     </div>
   )
Sign up to request clarification or add additional context in comments.

Comments

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.