问题描述
我需要根据另一列中的值在列中写入一个序列/索引。 请在下面找到示例来解释我的请求: 在这里,我需要根据颜色列中的值在 customindex 列中生成索引值..所以基本上如果列中有 4 行带有红色,那么它应该将行索引为 1,2,3,4 然后当它的 2 行以蓝色为值,它应该再次从 1 -> 1,2 索引。
输入数据:
[
{
"Type": "Header","Color": "Red","Customindex": "","code":"H1",},{
"Type": "Header","Color": "Blue","code":"H2",{
"Type": "LineItem","code":"L1","code":"L1"
},"code":"L2"
},"Color": "Yellow","code":"H3"
},"code":"L3"
},"code":"L2"
}
]
这是我需要帮助的转换:
%dw 2.0
output application/json
var TM = flatten(payload map ((item,index) ->
[{
"Type":payload.type,//HEADER VALUES
"Color":"","Customindex":"","code":"",}]++
[{
"Type":payload.type,// LINE ITEM VALUES
"Color":payload.color,"Customindex":index,//need the index sequence to only count similar colors
"code":"",}]))
---
(((TM distinctBy $ ... filters and groupings
包含详细信息的示例数据(这是预期的输出 - 应仅适用于订单项):
解决方法
这对你有用吗?
输入:
[
{
"Type": "Header","Color": "Red","Customindex": "","code": "H1"
},{
"Type": "Header","Color": "Blue","code": "H2"
},"Color": "Green","code": "H4"
},{
"Type": "LineItem","code": "L4"
},"code": "L1"
},"code": "L2"
},"Color": "Yellow","code": "H3"
},"code": "L3"
},"code": "L2"
}
]
脚本:
%dw 2.0
output application/csv
fun buildHeader(code) = {
'Type': 'Header',"Color": "","CustomIndex":"","Code":code
}
fun buildFirstLineItem(code,color,ci) = {
'Type': 'LineItem',"Color": color,"CustomIndex":ci,"Code":code replace ("H") with ("L")
}
---
flatten(payload orderBy $.code groupBy $.Color mapObject {
a: flatten($ map (
if($.'Type' == 'Header')
[buildHeader($.code)] + [buildFirstLineItem($.code,$.Color,(($$)+1))][0]
else
{
'Type': "LineItem","Color": $.Color,"CustomIndex": (($$)+1),"Code":$.code
}
))
}pluck($))
输出:
Type,Color,CustomIndex,Code
Type,Code
Header,H1
LineItem,Red,1,L1
LineItem,2,3,L1
Header,H2
LineItem,Blue,L2
LineItem,L2
Header,H3
LineItem,Yellow,L3
LineItem,L3
Header,H4
LineItem,Green,L4
LineItem,4,5,L4