Mule-Newbie
Mule-Newbie

Reputation: 109

How to sum values of same keys from objects in an array using Dataweave

The first key should remain as is, and the rest should be added as below output. The slash "/" is required at the end. This is just an example, the DataWeave script needs to be dynamic.

Input:

[
    {
        "a": "40",
        "b": "60",
        "c": "20/"
    },
    {
        "a": "40",
        "b": "10",
        "c": "10/"
    },
    
]

Output:

[
    {
        "a": "40",
        "b": "70",
        "c": "30/"
    }
    
]

Upvotes: 0

Views: 24

Answers (1)

aled
aled

Reputation: 25837

This is a weird structure however reduce() can be used to get each item in the list and the accumulator of the previous items, then mapObject() is used to sum the value of each key. The index parameter of mapObject() let us know if it is the first key of an object. Some ifs are needed for the conditions. Note that this solution assumes all the keys are the same in all items. The range selector [ ... to ... ] is used with an ending in -2 to remove the last character when it is a "/" for the sum, the it is added back after the addition.

%dw 2.0
output application/json
fun addValues(x: String, y: String)=
    if(x contains("/")) 
        ((x[0 to -2] as Number + y[0 to -2] as Number) as String ++ "/") 
    else 
        ((x as Number + y as Number) as String)
---
payload 
    reduce( 
        $$ mapObject ((value, key, index) -> 
            (key): if (index == 0) value 
                   else addValues($[key], value)
        )
    )

Output:

{
  "a": "40",
  "b": "70",
  "c": "30/"
}

Upvotes: 1

Related Questions