问题描述
我正在尝试将字符串数组转换为一个对象,每个成员都使用该字符串作为键,并将其值初始化为0。(经典的累加器用于字数统计,对吗?)
这是输入数据的样式:
%dw 2.0
output application/dw
var hosts = [
"t.me","thewholeshebang.com","thegothicparty.com","windowdressing.com","thegothicparty.com"
]
要获得累加器,我需要一个这种风格的结构:
var histogram_acc = {
"t.me" : 1,"thewholeshebang.com" : 1,"thegothicparty.com" : 2,"windowdressing.com" : 1
}
我以为这是reduce()的灌篮案例,对吧?
因此,要获取重复数据删除的主机列表,我们可以使用以下短语:
hosts distinctBy $
到目前为止开心。但是现在对我而言,它变得邪恶。
我认为这可能是黄金:
hosts distinctBy $ reduce (ep,acc={}) -> acc ++ {ep: 0}
但是问题在于,这种方法无法很好地解决。用于reduce()的lambda的第一个参数表示迭代元素,在这种情况下为端点或地址。 lambda将新对象附加到累加器。
好吧,那是我希望它会发生的方式,但是我得到了:
{
ep: 0,ep: 0,ep: 0
}
我需要它做得更好。
解决方法
正如您所说的reduce
非常适合此问题,或者,您可以使用对象的“动态元素”功能将“对象的数组展平为对象”
%dw 2.0
output application/dw
var hosts = [
"t.me","thewholeshebang.com","thegothicparty.com","windowdressing.com","thegothicparty.com"
]
---
{(
hosts
distinctBy $
map (ep) -> {"$ep": 0}
)}
请参见https://docs.mulesoft.com/mule-runtime/4.3/dataweave-types#dynamic_elements
, 方案1:
我认为在这种情况下的技巧是,您需要将 distinctBy ... map
的表达式括在 {}
中。
示例:
输入:
%dw 2.0
var hosts = [
"t.me","thegothicparty.com"
]
output application/json
---
{ // This open bracket will do the trick.
(hosts distinctBy $ map {($):0})
} // See Scenario 2 if you remove or comment this pair bracket
输出:
{
"t.me": 0,"thewholeshebang.com": 0,"thegothicparty.com": 0,"windowdressing.com": 0
}
方案2:如果从表达式 {}
中删除 {<expression distinctBy..map...}
,则输出将是一个数组
示例:
输入:
%dw 2.0
var hosts = [
"t.me","thegothicparty.com"
]
output application/json
---
//{ // This is now commented
(hosts distinctBy $ map {($):0})
//} // This is now commented
输出:
[
{
"t.me": 0
},{
"thewholeshebang.com": 0
},{
"thegothicparty.com": 0
},{
"windowdressing.com": 0
}
]
方案3:如果要计算每个项目的重复总数,可以使用 groupBy
和 sizeOf
示例:
输入:
%dw 2.0
var hosts = [
"t.me","thegothicparty.com"
]
output application/json
---
hosts groupBy $ mapObject (value,key) -> {
(key): sizeOf(value)
}
输出:
{
"t.me": 1,"thewholeshebang.com": 1,"thegothicparty.com": 2,"windowdressing.com": 1
}
,
很高兴(但可能仅对我来说)是我在写问题时发现了答案的事实。希望有人会提出同样的问题,这就是我的发现。
为了在示例(ep)中将lambda参数表示为结构中的键,我必须对其进行引用和内插。
"$ep"
一旦我这样做了,它就会快速进入:
hosts distinctBy $ reduce (ep,acc={}) -> acc ++ {"$ep": 0}
...然后当然是这样:
{
"t.me": 0,"windowdressing.com": 0
}