Warm tip: This article is reproduced from serverfault.com, please click

Skipping else part in dataweave 2.0

发布于 2020-12-17 17:07:47

I am trying to convert a groovy code into DataWeave. I am trying to store values in variable based on a condition. The pseudo code is as-

payload map (value, index) -> (
  if(condition) (
    vars.variableName + {
    "attribute1": "value1",
    "attribute2": "value2",
    "attribute3": "value3"
    }
  )
)

as you see that I don't want to use the else part. But in DW else part is mandatory.

So, is there any way that is can skip the else part. I tried this-

if(condition)(

)else{}

OR

if(condition)(

)else""

but this adds additional "" or {} in the variable

Questioner
Satyam Pisal
Viewed
0
short stack stevens 2020-12-19 01:11:00

You could just have the else be the preexisting variable without adding anything to it (needs initialized before this script).

payload map (value, index) -> (
  if(condition) (
    vars.variableName ++ {
    "attribute1": "value1",
    "attribute2": "value2",
    "attribute3": "value3"
    }
  )
  else vars.variableName
)

Or if vars.variableName hasn't been created yet you can default it to an empty object so you can add to it later in another script. However if the variable hasn't been initialized yet the condition in the if-else must direct the processing to the else clause. Otherwise you will get an error if trying to append an object to a variable that is null.

payload map (value, index) -> (
  if(condition) (
    vars.variableName ++ {
    "attribute1": "value1",
    "attribute2": "value2",
    "attribute3": "value3"
    }
  )
  else vars.variableName default {}
)

BTW need to use ++ to combine objects