gpt4 book ai didi

reduce - DataWeave 2.0 如何为 reduce() 构建动态填充的累加器

转载 作者:行者123 更新时间:2023-12-05 08:49:40 24 4
gpt4 key购买 nike

我试图将一个字符串数组转换为一个对象,每个成员都使用字符串作为键,并将值初始化为 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,
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

关于reduce - DataWeave 2.0 如何为 reduce() 构建动态填充的累加器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63514858/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com