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

Generate Parenthesis | Intuition + Code | Recursion Tree | Backtracking | Java

Problem Statement: Given n pairs of parentheses, write a function to generate all combinations of well-formed parentheses. Example…

3 months ago

Square Root of Integer

Given an integer A. Compute and return the square root of A. If A is…

1 year ago

Build Array From Permutation

Given a zero-based permutation nums (0-indexed), build an array ans of the same length where…

1 year ago

DSA: Heap

A heap is a specialized tree-based data structure that satisfies the heap property. It is…

2 years ago

DSA: Trie

What is a Trie in DSA? A trie, often known as a prefix tree, is…

2 years ago

Trees: Lowest Common Ancestor

What is the Lowest Common Ancestor? In a tree, the lowest common ancestor (LCA) of…

2 years ago