Rahul Sevani
Rahul Sevani

Reputation: 77

how to transpose csv in mule 4?

I have csv payload that looks like this

id,header,value
1,addr1,hyd
1,addr2,blr
2,addr1,rpr
2,addr2,knk
2,addr3,jpn

requirement is to transform the output payload to this

id,addr1,addr2,addr3
1,hyd,blr,
2,rpr,knk,jpn

I tried few approaches involving groupBy but not able to achieve desired output. This is how my groupBy is payload groupBy (item) -> item.id

Can someone please help me out? Thanks in advance.

Upvotes: 0

Views: 610

Answers (1)

user3078986
user3078986

Reputation:

%dw 2.0
output application/csv
// Get the distinct headers, maybe you want them ordered too
var headers = "id" >> (payload.*header distinctBy $ orderBy $)
// Get the rows but organize them so that you have objects {header: value}
var rows = payload groupBy $.id 
mapObject (
    {($$): 
        $ reduce (e, acc={id: $$}) -> acc ++ {(e.header): e.value}
    }
) 
pluck $
---
// Iterate over the rows
rows map (
    // Iterate over the headers and add the values
    headers reduce (e, acc={}) -> acc ++ {(e): $[e]}
)

Upvotes: 2

Related Questions