How to set a flag in array of objects and render items

Viewed 284

I am trying to render the particular object in an array. Where should i set the flag?Need Single loop

mappedData = (data) => {
return data.map((item) => {...logic}
}

Here is my sample object which returns

item:[
{id: 1, entry_id: 1, name: 'test', email: 'foo@bar.com', isFirst:true},
{id: 2, entry_id: 1, name: 'test', email: 'bar@foo.com', isFirst:false},
{id: 3, entry_id: 2, name: 'test', email: 'foo@bar.com', isFirst:true},
{id: 4, entry_id: 2, name: 'test', email: 'bar@foo.com', isFirst:false},
{id: 5, entry_id: 1, name: 'test', email: 'joe@ocean.com', isFirst:true},
{id: 6, entry_id: 2, name: 'test', email: 'foo@bar.com', isFirst:false},
{id: 7, entry_id: 2, name: 'test', email: 'foo@bar.com', isFirst:false},
];

How to set flag? and render 2 different div's which contains entry_id 1 in div and entry_id 2 in another div

render(){
return(
if(this.mappedData.entry_id =1){
<div>All entry_id 1 data should appear</div>
}
if(this.mappedData.entry_id =2){
<div>All entry_id 2  data should appear</div>
}

Most welcome on different solution with single loop

1 Answers

The simplest way I can think of is to have your two divs separately and then run individual loops in each with returning null (in your false case):

Code could look like this, (assuming item is your array):

<div>
{item.map((x) => {
  if(x.entry_id === 1){
      return <p>{x.name}</p>
  }
 return null;

})}
</div>
<div>
{item.map((x) => {
  if(x.entry_id === 2){
     return <p>{x.name}</p>
  }
 return null;
})}
</div>

If item is an object property, just replace item.map with data.item.map

Link

  1. You can also make separate loops at top by filtering and show them.
  2. You can also filter your array and then map inside the curly braces, if you are concerned about the null

EDIT:

OP wanted a solution with single loop. It can be achieved using this:


  let div1 = [];
  let div2 = [];

  item.forEach((x) => {
    if (x.entry_id === 1) {
      div1.push(<p key={x.email}>{x.name}</p>);
    } else {
      div2.push(<p key={x.email}>{x.name}</p>);
    }
  });

  return (
    <div className="App">
      {
        <>
          {div1}
          {div2}
        </>
      }
    </div>
  );

Updated Link

Related