Author: Abhishek Bathwal
The blog will help you to write a 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 are repeating with different values. We will check a dataweave script to group all 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" } ]
Note: Same Script can be used for dataweave version 1.
If any specific value is required on the basis of occurrence like the First Value or the Last value from the list for the key then an index can be used for that.
For getting 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" } ]
For getting 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" } ]