How to use Update operator in Dataweave 2.3 for Mule 4.3

Before the existence of update operator in Dataweave, If we need to update a value or field it is the most cumbersome task in cases where there are multiple fields or values to be updated or the message size is huge. The ideal approach is to create the object again and write the logic using map or mapObject of Dataweave. Now with the help of update operator updating values in nested arrays or objects has become easier.



Simple examples of update operator in Dataweave


Example 1:

To update a field in the given JSON object we can use update operator and update the value with or without specifying the condition



Dataweave Code:
%dw 2.0
output application/json
---
payload update {
case score at .score if(score == 30) -> score + 5
}

Also Read: How to make response downloadable as a file to user in MuleSoft


Example 2:

To update the field across all the objects in the JSON array we can use both map operator along with update operator and specify the condition


Dataweave Code:
%dw 2.0
output application/json
---
payload map ((user) ->
user update {
case price at .price if(price < 50) -> price + 30
}
)

Upserting a value is now simple using the update operator in Dataweave


The update operator also supports inserting a field if it doesn't exist by using ! symbol at the end of the selector expression. When the field is not present the value null is going to be bound to the variable.

Also Read: Filter keys with multiples values in the array from JSON message using Dataweave

Post a Comment

0 Comments