I try to get my head around the reduce function in Mulesoft Dataweave 2.0.
expected outcome:
{
"dev": "1",
"test": "2",
"uat": "3",
"prod": "4"
}
my dataweave code:
%dw 2.0
var invar = [
{"id": "1", "name": "dev"},
{"id": "2", "name": "test"},
{"id": "3", "name": "uat"},
{"id": "4", "name": "prod"}
]
output application/json
---
// invar reduce() ??? requirment: it must be done with reduce function.
Thanks
The trick is to set the accumulator to the correct value when DataWeave can not deduce it automatically:
%dw 2.0
var invar = [
{"id": "1", "name": "dev"},
{"id": "2", "name": "test"},
{"id": "3", "name": "uat"},
{"id": "4", "name": "prod"}
]
output application/json
---
invar reduce ((item, accumulator= {}) -> accumulator ++ {(item.name):item.id})
Initialise accumulator to empty object {} and add the formed key value pairs to the accumulator for the required output:
invar reduce ((item, accumulator = {}) -> accumulator ++ {(item.name): item.id } )
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.