When we create an object structure it is very useful to use dynamic elements. Dynamic elements can turn an object or array of objects into key and value pairs in an object constructor. The syntax of the dynamic element is that an object or array of objects is enclosed in parentheses ((...)
). We use this inside an object constructor enclosed in curly braces ({...}
) so we get the key/value pairs. The objects can be referenced by a variable or a function that returns an object.
In the following example we use dynamic elements to create a object with key/value pairs from an object and array of objects:
Source
%dw 2.0 var messageObj = { message0: { text: "Hello, DataWeave" } } fun message(index: Number, prefix:String , name: String): Object = { ("message" ++ index): { text: "$(prefix), $(name)" } } output application/json --- { // Dynamic element for a single object ({message: text: "Hello from object"}), // Dynamic element for a single object referenced by variable (messageObj), // Dynamic element for function that returns an object (message(1, "Goodbye", "Java")), // Dynamic element on array of expressions that return objects ([message(2, "Hi", "mrhaki"), message(3, "Good evening", "Hubert")]), // Simple key/value that will be part of the final object created_with: "DataWeave 2.4" }
Output
{ "message": { "text": "Hello from object" }, "message0": { "text": "Hello, DataWeave" }, "message1": { "text": "Goodbye, Java" }, "message2": { "text": "Hi, mrhaki" }, "message3": { "text": "Good evening, Hubert" }, "created_with": "DataWeave 2.4" }
Written with DataWeave 2.4.