typescript - 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 数组中
解决方案
使用 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>
推荐阅读
- list - Dart 中的混合类型列表
- elasticsearch - Elasticsearch 聚合 tophits - 扩展
- java - 什么字符串格式反序列化成 Map
通过 TypeReference 和杰克逊? - r - RStudio键盘快捷键将字符串转换为对象,反之亦然?(即删除或在名称周围添加引号)
- powerbi - 将 FILTER 添加到 AVERAGEX 函数会导致错误 Power BI
- java - 如何在 SSO 环境中为 Confluent 平台添加证书
- c# - 在 C# 中与 C 之间的元帅字符串
- java - 如何检查流中是否有图文电视?
- web - 在 Web 应用程序中使用 Web 程序集编译错误?
- javascript - socket.io client receives everything except for one emitter