else if Condition in flow (DataWeave 2.0)

If you’re familiar with popular languages like Java, or C#, you’ll notice the way DataWeave implements if/else is much closer to a ternary expression that the if/else statements you see in those languages. The difference is very simple, however. DW uses if/else expressions that returns values, Java and C# us if/else statements that do not return values.

If/else expressions can be chained together, meaning you can do multiple checks before you return any data. Here’s the format for how that works:

if (<criteria_expression1&gt;)
  <return_if_true&gt;
else if (<criteria_expression2&gt;)
  <return_if_true&gt;
else
  <return_if_no_other_match&gt;

You can have as many of these if/else chains as necessary.

You can chain several else expressions together within an if-else construct by incorporating else if. The following example uses the input var myVar = { country : "UK" }, which is defined by the myVar variable in the header. DataWeave Script:

%dw 2.0
var myVar = { country : "UK" }
output application/json
---
if (myVar.country =="USA")
 { currency: "USD" }
else if (myVar.country =="UK")
 { currency: "GBP" }
else { currency: "EUR" }

Output

{
  "currency": "GBP"
}

The following example is similar but takes an array as input instead of an object. The body of the script uses if else and else if statements within a do operation to populate the value of the hello variable. DataWeave Script:

%dw 2.0
output application/json
---
["Argentina", "USA", "Brazil"] map (country) -&gt; do {
  var hello = if(country == "Argentina") "Hola"
   else if(country == "USA") "Hello"
   else if(country == "Brazil") "Ola"
   else "Sorry! We don't know $(country)'s language."
   ---
   "$(hello) DataWeave"
}

Output:

[
  "Hola DataWeave",
  "Hello DataWeave",
  "Ola DataWeave"
]


Follow Me If you like my post please follow me to read my latest post on programming and technology. Instagram Facebook

Recent Posts

Find Intersection of Two Singly Linked Lists

You are given two singly linked lists that intersect at some node. Your task is…

4 months ago

Minimum Cost to Paint Houses with K Colors

A builder plans to construct N houses in a row, where each house can be…

4 months ago

Longest Absolute Path in File System Representation

Find the length of the longest absolute path to a file within the abstracted file…

4 months ago

Efficient Order Log Storage

You manage an e-commerce website and need to keep track of the last N order…

5 months ago

Select a Random Element from a Stream

You are given a stream of elements that is too large to fit into memory.…

5 months ago

Estimate π Using Monte Carlo Method

The formula for the area of a circle is given by πr². Use the Monte…

5 months ago