Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 256
learningMonk Avatar asked Jan 18 '26 12:01

learningMonk


1 Answers

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>
like image 87
Krzysztof Krzeszewski Avatar answered Jan 21 '26 03:01

Krzysztof Krzeszewski



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!