Home > OS >  Trying to map over array of objects in React, returning undefined
Trying to map over array of objects in React, returning undefined

Time:09-21

I'm trying to map over an array of objects. I don't understand why comment.commenter_comment is "undefined". I thought map and dot notation worked on objects if they were nested within an array, am I misunderstanding this?

I ultimately want to display "k" (commenter_comment: 'k') for the first loop, and so on...

import React from 'react';

export default function Comments(props) {
  var holder = []
  if (props.post && props.post.comments_text) {
   holder.push(Object.values(props.post.comments_text))

    return (
      <div>
        {holder.map((comment) => {
          return (
            <div>
               {comment.commenter_comment} 
            </div>
          )
        })}
      </div>
    )
  } else {
    return null;
  }
}

For reference, props looks like this:

props = {
    post: {
    comment: true,
    comments_text: 
        {
        -Mk0Bzc8T-p6ATuwn_2T: {commenter_comment: 'k', commenter_handle: 'SHARK1', commenter_uid: 
        '1lJQ2rVtzRdgp4K1SZJbXAopsfm1'}
        -Mk0CdvBkgIwfsZATPsS: {commenter_comment: 's', commenter_handle: 'SHARK1', commenter_uid: 
        '1lJQ2rVtzRdgp4K1SZJbXAopsfm1'}
        -Mk0Cht7il7Ohn6OiziB: {commenter_comment: 's', commenter_handle: 'SHARK1', commenter_uid: 
        '1lJQ2rVtzRdgp4K1SZJbXAopsfm1'}
        -Mk-AnrSJVU7sOmeVP_n: {commenter_comment: 'testing14', commenter_handle: 'SHARK1', 
         commenter_uid: '1lJQ2rVtzRdgp4K1SZJbXAopsfm1'}
    }
    handle: "bug1",
    key: "-MjLYDJlHXnO-HaL6R58",
    title: "k"
    }
}

Thank you for any help or tips.

CodePudding user response:

You're making your holder to be an array containing a single value, and that value will be the array of values from the object:

  var holder = []
  if (props.post && props.post.comments_text) {
   holder.push(Object.values(props.post.comments_text))

You want to map over all the object values, not the holder. While you could access holder[0], I think your code would be less confusing if you removed it entirely.

export default function Comments(props) {
    const comments = props.post?.comments_text;
    return !comments
        ? null
        : Object.values(comments).map(comment => (
            <div>
                {comment.commenter_comment}
            </div>
        ));
};

CodePudding user response:

You can try this

import React from 'react';
import {useState} from 'react';

export default function Comments(props) {
  const [holder, setHolder] = useState(Object.values(props.post.comments_text));

    return (
    holder.length != 0 ?
      <div>
        {holder.map((comment) => {
          return (
            <div>
               {comment.commenter_comment} 
            </div>
          )
        })}
      </div> : null
    )
}

  • Related