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

Select a Random Element from a Stream

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

2 days ago

Estimate π Using Monte Carlo Method

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

3 weeks ago

Longest Substring with K Distinct Characters

Given an integer k and a string s, write a function to determine the length…

3 weeks ago

Staircase Climbing Ways

There is a staircase with N steps, and you can ascend either 1 step or…

4 weeks ago

Autocomplete System Implementation

Build an autocomplete system that, given a query string s and a set of possible…

4 weeks ago

Job Scheduler Implementation

Design a job scheduler that accepts a function f and an integer n. The scheduler…

4 weeks ago