Update Operator

DataWeave supports the update operator, which enables you to update specified fields of a data structure with new values.

Overview

This operator is the one to use when you wish to change specific fields on an Object, while keeping all others the same.

Difference Between Update Function and Update Operator in Dataweave

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.

example

Here’s an example where update is used to increase a value and even insert a field using the upserting functionality (!):


Input

{
  "firstName": "Avery",
  "lastName": "Chance",
  "age": 56,
  "occupation": "Physicist"
}

DW Script

%dw 2.0
output json
---
payload update {
  case currentAge at .age ->  currentAge + 1
  case .status! -> "Retired"
}

Output

{
  "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:


Input

[
    {"name": "Ken (Leandro)", "age": 30},
    {"name": "Tomo", "age": 70},
    {"name": "Kajika", "age": 10}
]

DW Script

%dw 2.0
output json
---
payload map ((user, index) -> user  update {
        case name at .name if (name == "Tomo") -> name ++ " (Christian)"
})

Output

[
  {"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.

Follow Me

If you like my post please follow me to read my latest post on programming and technology.

Instagram

Facebook

Recent Posts

Generate Parenthesis | Intuition + Code | Recursion Tree | Backtracking | Java

Problem Statement: Given n pairs of parentheses, write a function to generate all combinations of well-formed parentheses. Example…

3 months ago

Square Root of Integer

Given an integer A. Compute and return the square root of A. If A is…

1 year ago

Build Array From Permutation

Given a zero-based permutation nums (0-indexed), build an array ans of the same length where…

1 year ago

DSA: Heap

A heap is a specialized tree-based data structure that satisfies the heap property. It is…

2 years ago

DSA: Trie

What is a Trie in DSA? A trie, often known as a prefix tree, is…

2 years ago

Trees: Lowest Common Ancestor

What is the Lowest Common Ancestor? In a tree, the lowest common ancestor (LCA) of…

2 years ago