Search

Dark theme | Light theme

September 27, 2022

DataWeave Delight: Add Conditionally Element to Array or Object

The core of DataWeave is to transform data from one format to another format. If we want to include an element in an array based on a condition we can enclose the element between parenthesis (element) followed by an if statement. If the condition of the if statement returns true the element is included in the array. To include a key/value pair in an object based on a condition we also enclose the key/value pair in parenthesis (key: value) and add an if statement. When the condition specified is true the key/value pair is added to the object, otherwise it will be left out.

In the following example we add conditionally the key website and each element of the array is added based on a condition. The conditions check values in a conf object defined at the top of the example:

Source

%dw 2.0

// Helper object with values used to add elements conditionally.
var conf = {
    kind: "FP",
    includeWebsite: true
}

output application/json
---
[
    ({
        language: "DataWeave", 
        kind: "Functional",
        // Add key/value to object if condition is true.
        (website: "https://docs.mulesoft.com/dataweave/2.4/") if conf.includeWebsite
    }) 
    // Add element to array if condition is true.
    if conf.kind == "FP", 
    
    ({
        language: "Java", 
        kind: "Object Oriented",
        (website: "https://www.java.com/") if (conf.includeWebsite)
    }) if (conf.kind == "OO")
]

Result

[
    {
        "language": "DataWeave",
        "kind": "Functional",
        "website": "https://docs.mulesoft.com/dataweave/2.4/"
    }
]

When we change the values in our conf object we get a different result:

Source

var conf = {
    kind: "OO",
    includeWebsite: false
}

Result

[
    {
        "language": "Java",
        "kind": "Object Oriented"
    }
]

Written with DataWeave 2.4.