1
votes

I am trying to loop through the array of objects. Value of this.state.saveFriendTag or this.props.userTags on console is:

Array of objects I am trying to loop through

State in constructor is: saveFriendTag: this.props.userTags? this.props.userTags: [],

Code is:

if(this.props.cardData){
  if (this.state.saveFriendTag.length == 1) {
    taggedFriendsBlue =  this.state.saveFriendTag.map((item, index) => {
      console.log(item,"item");
      return (
        <span className="displayedName blue" key={index}>{item.firstname}</span>
      )
    })
  } 

Error On Console

This is in return and taggedFriendsBlue is defined in render:

 <div className="pCard_contentContainer ">
     <textarea id="pcardTextarea" type="text" placeholder="Write Description here..." value={this.state.Description} onChange={this.textareaExpansion.bind(this)}></textarea>
       <If test={this.state.tagDone == true || this.state.saveFriendTag.length>0}>
       <div className="displayNames disp_inliFl">
         <span className="pcard_WithOne">-With</span>
           <div className="disp_inliFl">
               {taggedFriendsBlue}
           </div>
       </div>
    </If>
  </div>

Can anybody tell the reason for this console error? How to correct it?

1
Can you show full render method of the component? - ggderas
If the collection you are attempting to iterate is an Array, you don't have to specify Object.keys - Wolfie

1 Answers

2
votes

It looks like the issue is that you are using Object.keys on an array. You can remove that and just use .map directly.

Additionally, you need to specify a key for the span.

<span key={item.id} ... />

const array = [
  {
    firstName: "test",
    lastName: "test2"
  }
];

console.log(Object.keys(array));

As you can see from the code snippet, using Object.keys on an array will result in the index being passed on each iteration of the map function, instead of the object as you intend.