LittleMygler
LittleMygler

Reputation: 632

lodash groupBy object variable

I have an object looking something like this:

[
    {
        school: { name:"school1" state: {name:"washington" stateNr: 3} }
        nrOfStudents: 100
    },
    {
        school: { name:"school2" state: {name:"alaska" stateNr: 49} }
        nrOfStudents: 20
    },
    {
        school: { name:"school3" state: {name:"Texas" stateNr: 46} }
        nrOfStudents: 50
    },
    {
        school: { name:"school4" state: {name:"Texas" stateNr: 46} }
        nrOfStudents: 150
    }
]

And i want to group them by their state name.

[
    {
        stateName: "Texas";
        schools: [        
                     {
                          school: { name:"school4" state: {name:"Texas" stateNr: 46} }
                          nrOfStudents: 150
                     },
                     {
                          school: { name:"school3" state: {name:"Texas" stateNr: 46} }
                          nrOfStudents: 50
                     }
                  ]
    },
    {
        stateName: "Alaska"
        schools: [
                     {
                         school: { name:"school2" state: {name:"alaska" stateNr: 49} }
                         nrOfStudents: 20
                      }
                  ]
     }

and so on....

I have an object called something like SchoolByState that looks like those objects, and i want to match them into an array of SchoolByState

Upvotes: 0

Views: 87

Answers (1)

Ori Drori
Ori Drori

Reputation: 191976

Use lodash's _.flow() to create a function that groups by the state's name, and then maps the groups to the desired form:

const getSchoolByState = _.flow(
  arr => _.groupBy(arr, 'school.state.name'),
  groups => _.map(groups, (schools, stateName) => ({
    stateName,
    schools
  }))
)

const data = [{"school":{"name":"school1","state":{"name":"washington","stateNr":3}},"nrOfStudents":100},{"school":{"name":"school2","state":{"name":"alaska","stateNr":49}},"nrOfStudents":20},{"school":{"name":"school3","state":{"name":"Texas","stateNr":46}},"nrOfStudents":50},{"school":{"name":"school4","state":{"name":"Texas","stateNr":46}},"nrOfStudents":150}]

const result = getSchoolByState(data)

console.log(result)
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.11/lodash.min.js"></script>

Upvotes: 1

Related Questions