如何根据ID值合并2个字段,并确保该字段不可用

时间:2019-12-04 13:40:54

标签: dataweave

我正在尝试根据ID条件合并到数组字段。我进行了以下查询:

我期望CSV输出为:

ID,First Name,Last Name,Level,City,State
123,test,test1
456,test2,test3,level1,xyz,US

我现在得到的输出是:

ID,First Name,Last Name
123,test,test1
456,test2,test3,level1,xyz,US

如果您注意到,如果在第一条记录中不存在id值,则即使下一条后续记录具有值,标题也不会在csv中填充。 我的要求是获取“预期输出”。如果有人可以帮助您,它将非常有用。

注意:仅当第一条记录不匹配时,才会发生此问题。

%dw 2.0
output application/csv header = true
var a = [ {
"ID": "123",
"First Name": "test",
"Last Name": "test1"
},
{
"ID": "456",
"First Name": "test2",
"Last Name": "test3"
}
]

var b = [ {
"ID": "222",
"Level": "level1",
"City": "xyz",
"State": "US"
},
{
"ID": "555",
"Level": "level1",
"City": "xyz",
"State": "US"
},
{
"ID": "456",
"Level": "level1",
"City": "xyz",
"State": "US"
}]
---
a map (aValue) ->
{
"ID": aValue."ID" ,
"First Name": aValue."First Name",
"Last Name": aValue."Last Name",

(b filter ( aValue."ID" contains $."ID") map (bValue) -> {
"Level": bValue."Level",
         "City" : bValue."City",
         "State" : bValue."State"
})
}

1 个答案:

答案 0 :(得分:4)

CSV编写器通过查看第一项来定义标题,因此您需要确保它具有完整的密钥列表。一种方法是为第二个数组定义一个空对象,并在没有匹配项时始终合并它。请注意,我已经修改了脚本,以利用现成的连接功能:

%dw 2.0
import * from dw::core::Arrays
import * from dw::core::Objects

output application/csv header=true

var a = [ {
"ID": "123",
"First Name": "test",
"Last Name": "test1"
},
{
"ID": "456",
"First Name": "test2",
"Last Name": "test3"
}
]

var b = [ {
"ID": "222",
"Level": "level1",
"City": "xyz",
"State": "US"
},
{
"ID": "555",
"Level": "level1",
"City": "xyz",
"State": "US"
},
{
"ID": "456",
"Level": "level1",
"City": "xyz",
"State": "US"
}]

var emptyB = {
"Level": "",
"City": "",
"State": ""
}
---
leftJoin(a, b, (item) -> item.ID, (item) -> item.ID) 
    map ((item, index) -> item.l ++ ((item.r  default emptyB) - "ID"))