简体   繁体   中英

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.

We start by creating a map using the month value as the key. We then initialize the periodDays and expected values to zero.

For each object, we then add the periodDays and expected to get the sum for each.

Finally, we use Object.values() to turn our map into an array:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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