learningMonk
learningMonk

Reputation: 1411

how to groupby objects using lodash and map over the list -react

I have checked with other answers but not able to figure out my problem. I have tried with many things but ended up with error while mapping. it is my main data list example .

conlocations = [{mruCode:"1700", division:"Agricultural",country:"USA",...},{mruCode:"1000",division:"Agricultural",country:"CANADA",...},{mruCode:"1500",division:"Industrial",country:"AUSTRALIA",...}]

now i want to group country based on division means for division:"Agricultural" country:{"USA","CANADA"}. then i have to map grouped list . How to do that? It might be similar question but not able to get the result.

i have tried so far but getting error while mapping.

component code

render(){
        const _labels = store.getLabels();
        const {conLocations} = this.props;
        const groups= _.groupBy(conLocations,'division');
        console.log(groups);
        return (
            <table>
                <tbody>
                    {this.props.groups.map(grp=>conLocations.filter(element=>grp.division.includes(element.division)).map((element,index)=>{
                        <tr key={index}>
                        <td>{_labels[element.division]}</td>
                        <td>{element.country}</td>
                        </tr>
                    }))}
                </tbody>
            </table>
        );
    }

In UI, user can see like this -> Agricultural - USA,CANADA

Upvotes: 3

Views: 10708

Answers (2)

Krzysztof Krzeszewski
Krzysztof Krzeszewski

Reputation: 6778

In lodash _.groupBy actually creates an object with grouping parameter as keys, so you have to treat it as an object

const conLocations = [{
  mruCode: "1700",
  division: "Agricultural",
  country: "USA"
}, {
  mruCode: "1000",
  division: "Agricultural",
  country: "CANADA"
}, {
  mruCode: "1500",
  division: "Industrial",
  country: "AUSTRALIA"
}];

const groups = _.groupBy(conLocations, 'division');

Object.entries(groups).map(([key, value])=>{
  console.log("key:", key, "\nvalue:", value)
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.15/lodash.min.js"></script>

Upvotes: 4

Tien Duong
Tien Duong

Reputation: 2595

You just need to group by division then map the result to the format you want.

const groups = _(conLocations)
  .groupBy('division')
  .map((locations, division) => {
    const country = locations.map(location => location.country);
    return ({
      division,
      country,
    })
  })
  .value();

Above code will return the result in this format

[  
   {  
      division:'Agricultural',
      country:[  
         'USA',
         'CANADA'
      ]
   },
   {  
      division:'Industrial',
      country:[  
         'AUSTRALIA'
      ]
   }
]

Upvotes: 2

Related Questions