Dataweave: the absurd way of updating objects

Have you ever wondered how to change the value of one of your object's fields? Probably, and I'm sure you didn't wonder very long because that's the most basic function of a programming language : assignment.

How everyone does it

For context, let's quickly review how some of the most popular languages would update the id of a preexisting object.

C Using structures

my_object.id = 1

Javascript Using objects

myObject.id = 1

Java Using objects

myObject.id = 1

Python Using dictionnaries

my_object["id"] = 1

C# Using objects

MyObject.id = 1

I could keep going but I think you get my point. These are all very basic one-liners.

Now, let's have a look at how Dataweave, the "powerful tool" used as the main programming language in Mule projects, does this simple task.

How Dataweave does it

Assuming we are in a Message Transformer block, and we would like to update one of myObject's fields. Your first option is to reassign all the fields with their current value manually except the one you want to change:

%dw 2.0
output application/json
---
{
   "id": 1,
   "myFirstField": vars.myObject.myFirstField,
   "mySecondField": vars.myObject.mySecondField
}

You can already imagine the hassle this would be if we have a very large object with many attributes. Thankfully, Mulesoft came to the rescue, and offered us a new feature in Mule 4.3. 17 years after its first version, we can now use the update function. This how it looks like now.

%dw 2.0
output application/json
---
vars.myObject update {
  case .id -> 1
}

That is shorter, but could you think of a more intricate way of doing it? It feels like updating objects wasn't on the Mulesoft's roadmap so they improvised.

Anyway, I hope you learned how to be more productive thanks to this Dataweave operator.

1
Subscribe to my newsletter

Read articles from Hamza El Meknassi directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Hamza El Meknassi
Hamza El Meknassi