← All articles
DataWeave · MuleSoft · Quick Reads

DataWeave map vs mapObject: Choose by Output Shape

The easiest way to remember map versus mapObject is to start with the structure you are transforming.

Array to Array: map

Input:

[
  {"id":1,"name":"A"},
  {"id":2,"name":"B"}
]

Transformation:

%dw 2.0
output application/json
---
payload map ((item) -> {
  customerId: item.id,
  displayName: item.name
})

map iterates array elements and produces an array.

Object Entries: mapObject

Input:

{
  "firstName": "Sagar",
  "city": "Dallas"
}

Transformation:

%dw 2.0
output application/json
---
payload mapObject ((value, key) -> {
  (upper(key as String)): value
})

Conceptually:

{
  "FIRSTNAME": "Sagar",
  "CITY": "Dallas"
}

mapObject is useful when both keys and values matter.

Start with the Output Question

Ask:

Am I transforming a list of records? -> map
Am I transforming key/value entries? -> mapObject

If you find yourself converting an object to an array only to transform it and then rebuilding an object, check whether mapObject expresses the intent more directly.

Final Principle

Choose the operator that matches the data shape. map is naturally array-oriented; mapObject is naturally object-oriented.

CONTINUE READING

Explore closely related architecture, integration and implementation topics.