首页 > 解决方案 > lodash groupBy 对象变量

问题描述

我有一个看起来像这样的对象:

[
    {
        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
    }
]

我想按他们的州名对他们进行分组。

[
    {
        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....

我有一个类似于 SchoolByState 的对象,它看起来像那些对象,我想将它们匹配到一个 SchoolByState 数组中

标签: typescriptgroup-bylodash

解决方案


使用 lodash's_.flow()创建一个按州名分组的函数,然后将这些组映射到所需的形式:

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>


推荐阅读