Home > Enterprise >  Create element for each key in object in React
Create element for each key in object in React

Time:08-13

There is really 2 questions so I'm hoping that's okay to ask both within the 1 question on here.

In my application I have an object that looks like so:

{0: Array(39), 1: Array(2), 2: Array(2)}

and then as an example of one of them opened up:

1: Array(2)
0:
AttachmentId: null
Comment: "My comment reply to 19."
Commenter: {ItemId: 'bf13d14c-862d-eb11-80c1-00155d000001', Name: 'Tester'}
Id: 156
IsDeleted: false
LocalId: 42
MinorRevision: 1
ParentCommentId: 155
Recipients: []
Time: "2022-09-03T13:00:52 01:00"
[[Prototype]]: Object
1:
AttachmentId: null
Comment: "My comment 19."
Commenter: {ItemId: '64e5747a-7a32-4206-9bcb-3bfbeba99090', Name: ' '}
Id: 155
IsDeleted: false
LocalId: 40
MinorRevision: 1
ParentCommentId: null
Recipients: (3) [{…}, {…}, {…}]
Time: "2022-09-01T05:32:52 01:00"

Now in my jsx file, I am trying to create an element for each key in the object, so there should be 3 separate elements, however, it is only creating the one, this is what I have:

function Test(props) {
    for (const [key, value] of Object.entries(props.object)) {
    let rev = revision   key;
    let id = "rev-"   rev.replace('.', '-');
    return(
         <div id={id} className="rev-container">{props.object.Comment}</div>
        );
    }
}

const root = ReactDOM.createRoot(document.getElementById('my-comments'));

const element = <Test object = {filteredComments} />;

root.render(element);

Another issue I am having is accessing the "Comment" part of the objects, I thought I could just do something like I have done with the {pops.object.Comment} but obviously I am wrong with that as nothing is appearing within the div.

How do I fix these 2 issues? I'm not sure where it is that I am going wrong

CodePudding user response:

You have an object with the arrays. Let's use two loops. Also you should use map instead of for loop:

function Test({ object }) {
  return Object.entries(object).map(([key, arr]) => {
    return arr.map((comment) => {
      // let rev = revision   key;
      // let id = "rev-"   rev.replace(".", "-");
      return (
        <div key={comment.id} className="rev-container">
          {comment.Comment}
        </div>
      );
    });
  });
}

I commented out revision because it is not declared.

  • Related