Difference Between Update Function and Update Operator in Dataweave
The new Update function of Dataweave is beneficial to update an object. Below are some of the useful ways to use the update function.
Join the DZone community and get the full member experience.
Join For FreeThe new Update function of Dataweave is beneficial to update an object. Below are some of the useful ways to use the update function.
To use the update function, we need to import the package dw::util::Values. The other functions available in this package are attr, mask, index, field. I am providing an example of how we can use the update function in this article.
The update function can be used to update an element of each object in an array. In the below example, we have an array of employees. Each employee has an employee name, age, ServiceDetails. ServiceDetails is again an array. If we want to update the designation element of ServiceDetails, we can use the below data weave. This will update all the elements of the array.
Input:
[
{
"EmpName": "John",
"Age": "32",
"ServiceDetails":{
"Designation": "Clerk",
"DOJ": "Sept 20 1998"
}
},
{
"EmpName": "Chrissy",
"Age": "32",
"ServiceDetails":{
"Designation": "Clerk",
"DOJ": "Sept 20 2000"
}
},
{
"EmpName": "Kelvin",
"Age": "33",
"ServiceDetails":{
"Designation": "Accountant",
"DOJ": "Sept 20 2015"
}
}
]
Dataweave Code for Update function:
xxxxxxxxxx
%dw 2.0
import * from dw::util::Values
output application/json
---
payload.ServiceDetails update "Designation" with "Teacher"
Output:
xxxxxxxxxx
[
{
"Designation": "Teacher",
"DOJ": "Sept 20 1998"
},
{
"Designation": "Teacher",
"DOJ": "Sept 20 2000"
}
{
"Designation": "Teacher",
"DOJ": "Sept 20 2015"
}
]
As the output shows, the Designation of all elements is updated with Teacher.
Using the Update Operator
Update operator is used to updating specified fields of a data structure with new values.
If the requirement is to update an element on some condition, we use the update operator. Like in the above input, I would like to update the designation with "Assistant Manager" if the designation is "Clerk." Below is the dataweave code:
xxxxxxxxxx
%dw 2.0
output application/json
---
payload map ((item) ->
item.ServiceDetails update {
case Designation at .Designation if (Designation == "Clerk") -> "Assistant Manager"
})
Output:
xxxxxxxxxx
[
{
"Designation": "Assistant Manager",
"DOJ": "Sept 20 1998"
},
{
"Designation": "Assistant Manager",
"DOJ": "Sept 20 2000"
},
{
"Designation": "Accountant",
"DOJ": "Sept 20 2015"
}
]
I would be happy to answer any questions.
Opinions expressed by DZone contributors are their own.
Comments