简体   繁体   中英

React, render array in different divs, depending on the condition

For example we have the array of objects;

let arr = [
    {id: 10, name: 'hello10'}, 
    {id: 10, name: 'hello10'},
    {id: 13, name: 'hello13'},
    {id: 16, name: 'hello16'},
    {id: 17, name: 'hello17'},
    {id: 17, name: 'hello17'},
    {id: 17, name: 'hello17'}
];

After I will make array map how can get the structure below in React? And this should be generic, because we don't know about id's we will get.

<div>
    <p>hello10</p>
    <p>hello10</p>
</div>
<div>
    <p>hello13</p>
</div>
<div>
    <p>hello16</p>
</div>
<div>
    <p>hello17</p>
    <p>hello17</p>
    <p>hello17</p>
</div>

Try with grouping your data by id first:

Object.values(
  arr.reduce((acc, item) => ({
    ...acc,
    [item.id]: (acc[item.id] || []).concat(item),
  }), {})
).map(group => (
  <div>
    {group.map(item => (
      <p>{item.name}</p>
    ))}
  </div>
))

You could group in advance and then render the result with the tags.

 var array = [ { id: 10, name: 'hello10' }, { id: 10, name: 'hello10' }, { id: 13, name: 'hello13' }, { id: 16, name: 'hello16' }, { id: 17, name: 'hello17' }, { id: 17, name: 'hello17' }, { id: 17, name: 'hello17' }], grouped = array.reduce((r, o, i, a) => { if (o.id === (a[i - 1] && a[i - 1].id)) { r[r.length - 1].push(o); } else { r.push([o]); } return r; }, []); console.log(grouped); 
 .as-console-wrapper { max-height: 100% !important; top: 0; } 

You can try this

let dict = {};
let idArr = [];

const len = arr.length;

//We are grouping our data by id
arr.map((ar) =< {
    if(!dict[ar.id]){
        dict[arr[i].id] = [];
        idArr.push(arr[i].id);
    }
    dict[arr[i].id].push(arr[i]);
});

// Now we will generate the output
idArr.map((id) => {
    return <div>{dict[id].map((elem) => <p>{elem}</p>)}</div>
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM