javascript - 对象数组 - 根据其中的值划分信息
问题描述
我有一个对象数组:
const array = [ {
"Type": "DefinedBenefitPension",
"Description": null,
"Year": 2016,
"Participants": 9.0,
"TotalAssets": 6668305.0,
"NetAssets": 6668305.0,
"PlanName": null
},
{
"Type": "DefinedContributionPension",
"Description": null,
"Year": 2016,
"Participants": 72.0,
"TotalAssets": 17230395.0,
"NetAssets": 17230395.0,
"PlanName": null
},
{
"Type": "DefinedBenefitPension",
"Description": null,
"Year": 2017,
"Participants": 7.0,
"TotalAssets": 2096999.0,
"NetAssets": 2096999.0,
"PlanName": null
}...
];
这只是一小部分数据。有很多不同的类型(不仅是DefinedBenefitPension
and DefinedContributionPension
)。我制作了一个包含所有唯一类型的数组:
const uniquePensionTypes = data => {
const unique = [...new Set(data.map(plan => plan.Type))];
return unique;
};
我将原始数组作为数据传递的地方。现在我需要按照相同的类型Participants
进行划分。TotalAssets
在这个例子中,我需要调用数组definedBenefitPension
DefinedBenefitPensionParticipants = [9,7]
DefinedContributionPensionParticipants = [72]
我怎样才能做到这一点?
解决方案
Ifdata
是整个对象数组。
data.reduce( ( resObj, item ) => ({
...resObj,
[ item.Type ]: [
...( resObj[ item.Type ] || [] ),
item.Participants
]
}), {})
这会给你一个像
{
DefinedBenefitPension:[9,7],
DefinedContributionPension:[72]
}
推荐阅读
- apache-kafka - 没有输入主题的拓扑将不会创建流线程和全局线程
- c# - 服务器响应中的 DateTime.UtcNow 显示比响应后客户端调用的 DateTime.UtcNow 更晚的时间
- git - 使用本地 Git LFS 存储库检查是否有任何文件更改而无需在 .git 下复制
- python - 多个用户输入和他们的第二个输入
- python - GET 请求的格式
- apache-kafka - Apache Kafka 与 HTTP API
- r - Shiny R中的密度图未按预期工作
- java - java.lang.NoClassDefFoundError: org/apache/poi/xssf/usermodel/XSSFRow
- flutter - Flutter 在滚动时将容器保持在顶部
- talend - 使用 Talend 删除最旧的数据