Home > Software design >  how to print items of sub array using map function
how to print items of sub array using map function

Time:09-26

This is the code i am trying to print out the comments through map function but cant figure out how:

class Postcomment2 extends React.Component {
uploadcomment = () => {
  return this.props.post.comments.map((commentz) => {
    return <div>{this.props.post.comments["comment"]}</div>;
  }); /* How to access sub array of comments and print them all */
};

render() {
  return (
    <div>
      <div>{this.uploadcomment()}</div>
    </div>
  );
}
}

in this Post is the array of objects and the data is:

{
imageUrl:
  "https://i.pinimg.com/originals/83/6c/8a/836c8a66349fecbc0a06c4cc3d41e031.jpg",
user: Users[0].user,
likes: 410,
caption:
  "Here at kingdom tower... #KSA #KingdomTower #React JS #This is getting too long #Peace",
profilepic: Users[0]["image"],
comments: [
  {
    user: "zoraiz",
    comment: "Nicee!"
  },
  {
    user: "asher",
    comment: "Alrightttt!!"
  },
  {
    user: "hamis",
    comment: "Interesting...."
  }
]

},

CodePudding user response:

uploadcomment = () => {
    const { comments } = this.props.post;

    return (
      <div>
         {comments.map(comment => {
             console.log(comment.user, comment.comment)
             return true;
         })}
      </div>
    )

This should now print out every comment's user and comment. Change the return to whatever JSX you wish to render.

Before, you were mapping over the comments, and every iteration you got 'commentz' which you weren't even using inside of the map. This is the current 'comment' in the iteration of the map, so you basically have access to it and it's properties such as user and comment.

When you tried to do this.props.post.comments["comment"] previously, this was saying basically, every iteration, get comments.comment, however, comments is an array not an object.

CodePudding user response:

You need to first Traverse the Post array and after that traverse the subArray comment. Please find the codeSandbox link

  • Related