mapObject function in DataWeave 2.0 (mulesoft)

The mapObject function is used to transform the data contained in an object. It does this by iterating over each key/value pair in the object and applying a transformation to each key and value. It takes in an Object, and a lambda that takes in 3 parameters, a value, key, and index, and returns a new Object. Finally, the entire function returns an Object.


mapObject(Object<K,V>, (V,K,Number) -> Object): Object

mapObject<K, V>(@StreamCapable object: { (K)?: V }, mapper: (value: V, key: K, index: Number) -> Object): Object

We use mapObject when we want to change the keys and/or values on an Object to be something else.

Example

This example iterates over the input { "a":"b","c":"d"} and uses the anonymous mapper function ((value,key,index) → { (index) : { (value):key} }) to invert the keys and values in each specified object and to return the indices of the objects as keys. The mapper uses named parameters to identify the keys, values, and indices of the input object. Note that you can write the same expression using anonymous parameters, like this: {"a":"b","c":"d"} mapObject { ($$$) : { ($):$$} }

Source

%dw 2.0
output application/json
---
{"a":"b","c":"d"} mapObject (value,key,index) -> { (index) : { (value):key} }

Output

{ "0": { "b": "a" }, "1": { "d": "c" } }

Input

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

DW Script

%dw 2.0
output json
---
payload mapObject (value, key, index) -> {
  (upper(key)): value
}

Output

{
  "FIRSTNAME": "Avery",
  "LASTNAME": "Chance",
  "AGE": 56,
  "OCCUPATION": "Physicist"
}

The parentheses around upper(key) are required to make the key dynamic, as seen in previous sections.

Follow Me

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

Instagram

Facebook

Recent Posts

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…

1 year ago

DSA: Trie

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

1 year ago

Trees: Lowest Common Ancestor

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

1 year ago

Binary Search Tree (BST)

A Binary Search Tree (BST) is a type of binary tree that satisfies the following…

1 year ago