I have an input payload containing array of objects where I need to group-by
id-key and form 2 arrays of objects based on id-key. See below details.
input Payload:
{
"id": {
"header_id": "460",
"id-branch": {
"branch-name": "genaral motors",
"req-name": "genaral motors",
"id-key": "0791",
"id-lines": {
"id-key": "0791",
"productId": "463"
}
},
"id-branch": {
"branch-name": "genaral motors",
"req-name": "genaral motors",
"id-key": "9692",
"id-lines": {
"id-key": "9692",
"productId": "464"
},
"id-lines": {
"id-key": "9692",
"productId": "465"
}
}
}
}
desired Ouput:
[
{
"branch-name": "genaral motors",
"req-name": "genaral motors",
"type": "dhl",
"lines-ids": "swr",
"lines": [
{
"productId": "463"
}
]
},
{
"branch-name": "genaral motors",
"req-name": "genaral motors",
"type": "dhl",
"lines-ids": "swr",
"lines": [
{
"productId": "464"
},
{
"productId": "465"
}
]
}
]
the output has to be generated as array of object which groups productId which are under same id-key.
Assuming that the keys are already grouped by product id, I used filterObject() to remove the keys that are not required, then use pluck() to pick the values into an array. After that I removed keys from each element that are not used in the output. The keys added I assumed that were literal since no indication was given. For clarity I implemented a function to encapsulate the mapping of the lines.
%dw 2.0
output application/json
fun updateLines(x)=
x - "id-lines" ++ {lines: x.*"id-lines" map {productId: $.productId}}
---
payload.id
filterObject ((value, key, index) -> key as String == "id-branch")
pluck ($)
map (updateLines($) - "id-key" ++ { "type": "dhl", "lines-ids": "swr"})
Output:
[
{
"branch-name": "genaral motors",
"req-name": "genaral motors",
"lines": [
{
"productId": "463"
}
],
"type": "dhl",
"lines-ids": "swr"
},
{
"branch-name": "genaral motors",
"req-name": "genaral motors",
"lines": [
{
"productId": "464"
},
{
"productId": "465"
}
],
"type": "dhl",
"lines-ids": "swr"
}
]