首页 > 解决方案 > 对象数组 - 根据其中的值划分信息

问题描述

我有一个对象数组:

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
        }...
    ];

这只是一小部分数据。有很多不同的类型(不仅是DefinedBenefitPensionand DefinedContributionPension)。我制作了一个包含所有唯一类型的数组:

const uniquePensionTypes = data => {
    const unique = [...new Set(data.map(plan => plan.Type))];
    return unique;
};

我将原始数组作为数据传递的地方。现在我需要按照相同的类型Participants进行划分。TotalAssets在这个例子中,我需要调用数组definedBenefitPension

DefinedBenefitPensionParticipants = [9,7]
DefinedContributionPensionParticipants = [72]

我怎样才能做到这一点?

标签: javascriptarraysreactjssorting

解决方案


Ifdata是整个对象数组。

data.reduce( ( resObj, item ) => ({
  ...resObj,
  [ item.Type ]: [
    ...( resObj[ item.Type ] || [] ),
    item.Participants
  ]
}), {})

这会给你一个像

{
    DefinedBenefitPension:[9,7],
    DefinedContributionPension:[72]
}

推荐阅读