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.
Problem Statement: Given n pairs of parentheses, write a function to generate all combinations of well-formed parentheses. Example…
Given an integer A. Compute and return the square root of A. If A is…
Given a zero-based permutation nums (0-indexed), build an array ans of the same length where…
A heap is a specialized tree-based data structure that satisfies the heap property. It is…
What is the Lowest Common Ancestor? In a tree, the lowest common ancestor (LCA) of…