Introduced in DataWeave 2.3.0. Supported by Mule 4.3 and later.
Versions prior to Mule 4.3 require the following syntax to increase the age
value in myInput
by one without recreating the entire object:
%dw 2.0
var myInput = {
"name": "Ken",
"lastName":"Shokida",
"age": 30
}
output application/json
---
myInput mapObject ((value,key) ->
if(key as String == "age")
{(key): value as Number + 1}
else
{(key): value} )
In Mule 4.3, the update
operator simplifies the syntax:
%dw 2.0
var myInput = {
"name": "Ken",
"lastName":"Shokida",
"age": 30
}
output application/json
---
myInput update {
case age at .age -> age + 1
}
Both DataWeave scripts return the same result:
{
"name": "Ken",
"lastName": "Shokida",
"age": 31
}
With update
, casting or iterating through all the key-value pairs is not necessary.
The update
syntax is as follows:
<value_to_update> update {
case <variable_name> at <update_expression>[!]? [if(<conditional_expression>)]? -> <new value>
...
}
%dw 2.0
output application/json
---
payload map ((item) ->
item.ServiceDetails update {
case Designation at .Designation if (Designation == "Clerk") -> "Assistant Manager"
})
[
{
"Designation": "Assistant Manager",
"DOJ": "Sept 20 1998"
},
{
"Designation": "Assistant Manager",
"DOJ": "Sept 20 2000"
},
{
"Designation": "Accountant",
"DOJ": "Sept 20 2015"
}
]
value_to_update
represents the original value to update.update_expression
is the selector expression that matches a value in value_to_update
.variable_name
is the name of the variable to bind to the matched update_expression
value.new_value
is the expression with the new value.[if(<conditional_expression>)]?
If conditional_expression
returns true
, the script updates the value. Use of a conditional expression is optional.[!]
marks the selector as an upsert. If the expression doesn’t find a match, the !
makes the update
operator create all the required elements and insert the new value.update_expression
supports multiple case
expressions.Note The update operator doesn’t mutate the existing value. Instead, the operator creates a new value with the updated expressions. |
If you like my post please follow me to read my latest post on programming and technology.
You are given a stream of elements that is too large to fit into memory.…
The formula for the area of a circle is given by πr². Use the Monte…
Given an integer k and a string s, write a function to determine the length…
There is a staircase with N steps, and you can ascend either 1 step or…
Build an autocomplete system that, given a query string s and a set of possible…
Design a job scheduler that accepts a function f and an integer n. The scheduler…