Home > OS >  How to map within a map in React
How to map within a map in React

Time:03-23

I am trying to map parent comments and then within the map function I want to map the corresponding nested child comments that are only one level deep.

For some reason when I try to do this all the nested child comments display below the first parent comment.

I have two arrays:

parentComments: [
{
  id: "1",
  comment: "First parent comment"
},
{
  id: "2",
  comment: "Second parent comment"
},
]

childComments: [
{
  id: "3",
  comment: "First child comment",
  parentCommentId: "1"
},
{
  id: "4",
  comment: "Second child comment",
  parentCommentId: "2"
},
]

Here is the code I am trying:

{parentComments.map((parentComment) => (
    <ul>
            {parentComment.comment}
            <li>
              {" "}
              {childComments.map((childComment) => (
                <>
                  {childComments.find(
                    (e) => e.parent_comment_id === comment.id
                  )
                    ? childComment.comment
                    : ""}
                </>
              ))}
            </li>
          </ul>
))}

What I would expect to happen is each parent comment is mapped through, if a child comments parentCommentId equals the id of the parent comment being mapped, it would display the child comment below it.

CodePudding user response:

At first make new array like this then

let parentComments =[
  {
    id: "1",
    comment: "First parent comment"
  },
  {
    id: "2",
    comment: "Second parent comment"
  },
]

let childComments= [
  {
    id: "3",
    comment: "First child comment",
    parentCommentId: "1"
  },
  {
    id: "4",
    comment: "Second child comment",
    parentCommentId: "2"
  },
];
let mapArray =parentComments.map(p => ({
    ...p,
    childComments : childComments.filter(c => c.parentCommentId ==p.id)
}));
console.log(mapArray);
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>

then you can try

{parentComments.map((parentComment) => (
    <ul>
            {parentComment.comment}
            <li>
              {" "}
              {childComments.map((childComment) => (
                <>
                  childComment.comment
                    }
                </>
              ))}
            </li>
          </ul>
))}
  • Related