我尝试了解 Mulesoft Dataweave 2.0 中的归约函数。
预期结果:
{
"dev": "1",
"test": "2",
"uat": "3",
"prod": "4"
}
我的数据编织代码:
%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.
谢谢
技巧是当 DataWeave 无法自动推导累加器时将其设置为正确的值:
%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})
将累加器初始化为空对象{},并将形成的键值对添加到累加器中以获得所需的输出:
invar reduce ((item, accumulator = {}) -> accumulator ++ {(item.name): item.id } )
Reduce 适用于数组,并不断累积每次数组迭代,并在处理完成后返回。在您的示例中,我使用空对象 {} 初始化累加器,并且在每次迭代中,我使用 item.name 作为对象键,使用 item.id 作为值。
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
})
%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, acc = {}) -> acc ++ {(item.name) : item.id})