如何解决等效和不匹配时改进leftJoin嵌套的mapObject
我正在使用以下dataweave
函数,并且确实可以使用。
%dw 2.0
import * from dw::core::Arrays
output application/json
var mysqlInvoices = [
{
"id": 1,"owner": "Joseph"
},{
"id": 2,"owner": "Maria"
}
]
var sapInvoices = [
{
"number": 3,"issuedBy": "XYZ"
},{
"number": 4,"issuedBy": "ABC"
}
]
---
leftJoin(mysqlInvoices,sapInvoices,(m) -> m.id,(s) -> s.number) map (item,index) ->
(item.l mapObject (sItem,sKey) ->
(if ((sKey) as String == "id") "identifier"
else if ((sKey) as String == "owner") "ownerName"
else (sKey)): sItem)
++
(if (item.r != null)
item.r mapObject (sItem,sKey) ->
(sKey): sItem
else
sapInvoices[0] mapObject
(sItem,sKey) -> (sKey): "")
但是,我正在考虑是否可以在两点上改进此功能:
- 更改关键条件:
我认为这不是检查每个键是否匹配的最佳实践:
(if ((sKey) as String == "id") "identifier"
else if ((sKey) as String == "owner") "ownerName"
else (sKey)): sItem
- 当
leftJoin
与键不匹配时,使用原始对象将其映射为空字符串:
sapInvoices[0] mapObject (sItem,sKey) ->
(sKey): ""
我对这两点感到不舒服,并且我相信有很多方法可以改进此代码,我只是不知道如何。
如果执行同一任务的方式非常不同,我也很喜欢这种建议。
解决方法
尝试以下操作,如果有什么话,代码似乎更简单:
%dw 2.0
import * from dw::core::Arrays
output application/json
var mysqlInvoices = [
{
"id": 1,"owner": "Joseph"
},{
"id": 2,"owner": "Maria"
}
]
var sapInvoices = [
{
"number": 3,"issuedBy": "XYZ"
},{
"number": 4,"issuedBy": "ABC"
}
]
var fs2rn = {
id: "identifier",owner: "ownerName"
}
var rightEmpty= {number:"",issuedBy:""}
---
leftJoin(
// Do the field renaming at the very begining
mysqlInvoices map ($ mapObject {(fs2rn[$$] default $$): $}),sapInvoices,(m) -> m.identifier,(s) -> s.number
)
// Iterate over the results
// Get just the values,and colapse the objects into a single object
map (
{($ pluck $)}
)
// Iterate over the results and use pattern-matching to
//
map (
$ match {
// Check if you have an id but not a number fields
// In which case add the rightEmpty object
case o if (o.identifier? and not (o.number?)) -> o ++ rightEmpty
// Or give the object because you now have both an id and a number
else o -> o
}
)
我使用的功能是:
- 动态元素,documentation
-
pluck
,documentation - 使用
match
运算符documentation 进行模式匹配
如果我要给您一个建议,那将是更好地缩进您的代码。尽管如此,做得还不错!
,根据乔治的回答,您可以删除匹配和匹配,并直接组合左右表。见下文:
ORACLE_SID
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。