DataWeave script for grouping multiple values of the same key

  • July 30, 2021

This tech article will help you write a DataWeave script for grouping Multiple values associated with the same Key.

Input (in CSV format):

Id,Value
1,a
2,b
3,c
1,d
2,e
3,f
1,g

In the above input, Id – 1,2,3 repeat with different values. Check a DataWeave script to group these values to their respective ID.

DataWeave script:

%dw 2.0
output application/json
---
(payload groupBy ((item,index) -> item.Id) mapObject ((val, key) ->
   group : {
       Id : key,
       Value : val.Value joinBy ","
})).*group

Output:

[
 {
   "Id": "1",
   "Value": "a,d,g"
 },
 {
   "Id": "2",
   "Value": "b,e"
 },
 {
   "Id": "3",
   "Value": "c,f"
 }
]

Dataweave Script

NOTE: The same script can be used for DataWeave version 1.

If any specific value is required based on occurrence, such as the first value or the last value from the list for the key, then you can use an index for that.

To get the first value:

%dw 2.0
output application/json
---
(payload groupBy ((item, index) -> item.Id) mapObject ((val, key) ->
   group : {
       Id : key,
       Value : (val.Value joinBy ",")[0]
}) orderBy ($.Id)).*group

Output:

[
 {
   "Id": "1",
   "Value": "a"
 },
 {
   "Id": "2",
   "Value": "b"
 },
 {
   "Id": "3",
   "Value": "c"
 }
]

To get the last value:

%dw 2.0
output application/json
---
(payload groupBy ((item, index) -> item.Id) mapObject ((val, key) ->
   group : {
       Id : key,
       Value : (val.Value joinBy ",")[-1]
}) orderBy ($.Id)).*group

Output:

[
 {
   "Id": "1",
   "Value": "g"
 },
 {
   "Id": "2",
   "Value": "e"
 },
 {
   "Id": "3",
   "Value": "f"
 }
]

— By Abhishek Bathwal