DataWeave supports the update
operator, which enables you to update specified fields of a data structure with new values.
This operator is the one to use when you wish to change specific fields on an Object, while keeping all others the same.
Update Function in Dataweave
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. The update function can be used to update an element of each object in an array.
Update Operator in Dataweave
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.
Here’s an example where update
is used to increase a value and even insert a field using the upserting functionality (!
):
{
"firstName": "Avery",
"lastName": "Chance",
"age": 56,
"occupation": "Physicist"
}
%dw 2.0
output json
---
payload update {
case currentAge at .age -> currentAge + 1
case .status! -> "Retired"
}
{
"firstName": "Avery",
"lastName": "Chance",
"age": 57,
"occupation": "Physicist",
"status": "Retired"
}
Notice that you can capture the values into variables, as with currentAge
. This is important because it allows using the value as part of the new one and even evaluating conditions. Let’s see an example:
[
{"name": "Ken (Leandro)", "age": 30},
{"name": "Tomo", "age": 70},
{"name": "Kajika", "age": 10}
]
%dw 2.0
output json
---
payload map ((user, index) -> user update {
case name at .name if (name == "Tomo") -> name ++ " (Christian)"
})
[
{"name": "Ken (Leandro)", "age": 30},
{"name": "Tomo (Christian)", "age": 70},
{"name": "Kajika", "age": 10}
]
So far we’ve worked with flat Objects, but the update
operator allows selecting fields no matter how nested the Object structure is.
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…