简体   繁体   English

如何根据条件添加对象数组的值? JS

[英]How to Add the values ​of an object array based on a condition? JS

I am looking to sum the fields of my objects according to a value of my object我正在寻找根据我的对象的值对我的对象的字段求和

For example, i have an array:例如,我有一个数组:

   [
    {
        "month": 4,
        "periodDays": 1,
        "expected": 5
    },
    {
        "month": 5,
        "periodDays": 10,
        "expected": 40
    },
    {
        "month": 5,
        "periodDays": 11,
        "expected": 35
    },

    {
        "month": 6,
        "periodDays": 8,
        "expected": 20
    }
]

and i want:而且我要:

  [
{
    "month": 4,
    "periodDays": 1,
    "expected": 5
},
{
    "month": 5,
    "periodDays": 21,
    "expected": 75
},
{
    "month": 6,
    "periodDays": 8,
    "expected": 20,
},

I know I can use the reducer but I can't make it work with a condition.我知道我可以使用减速器,但我不能让它在有条件的情况下工作。

You can use Array.reduce() to create the desired result.您可以使用Array.reduce()创建所需的结果。

We start by creating a map using the month value as the key.我们首先使用month值作为键创建地图。 We then initialize the periodDays and expected values to zero.然后我们将 periodDays 和期望值初始化为零。

For each object, we then add the periodDays and expected to get the sum for each.对于每个对象,我们然后添加 periodDays 并期望得到每个对象的总和。

Finally, we use Object.values() to turn our map into an array:最后,我们使用Object.values()将我们的地图变成一个数组:

 let input = [ { "month": 4, "periodDays": 1, "expected": 5 }, { "month": 5, "periodDays": 10, "expected": 40 }, { "month": 5, "periodDays": 11, "expected": 35 }, { "month": 6, "periodDays": 8, "expected": 20 } ] const result = Object.values(input.reduce((acc, { month, periodDays, expected }) => { acc[month] = acc[month] || { month, periodDays: 0, expected: 0 }; acc[month].periodDays += periodDays; acc[month].expected += expected; return acc; }, {})); console.log('Result:', result)
 .as-console-wrapper { max-height: 100% !important; }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM