Contact Us 1-800-596-4880

Map Objects Key

This DataWeave example uses the mapObject function to iterate through an array of objects and appends a new object that matches the value of the specified criteria.

Before you begin, note that DataWeave version 2 (%dw 2.0) is for Mule 4 apps. For a Mule 3 app, refer to DataWeave version 1 (%dw 1.0) examples, within the Mule 3.9 documentation set. For other Mule versions, you can use the Mule Runtime version selector in the table of contents.

The input consists of a JSON object with sheets. The value of every sheet (for example, (sheet)1, (sheet)2) is an array of objects. The DataWeave script adds another object append as the last item to the matched sheet array if the sheet number equals to the value of the Id key of the append object. The example uses the function fun extractNumber to extract the sheet number from the sheet page name pageName. Then the DataWeave function mapObject iterates over every sheet in the root, and if the extractNumber equals to the append.Id value, the function adds the append object to the matched sheet object.

DataWeave Script:
%dw 2.0
output application/json

var append =
    {
    "Id": "2",
    "Access": "4444",
    "Subteam": "1",
    }

fun extractNumber(pageName: Key) =
     (pageName as String match  /\(sheet\)([0-9]+)/)[1]
---
payload mapObject ((value, key, index) -> do {
        if(extractNumber(key) == append.Id)
            {(key): value << append}
         else
            {(key): value}
})
Input JSON Payload:
{
"(sheet)1": [
{
  "Id": 1.0,
  "Team": "Mule",
  "timestamp": "2019-09-26T16:37:54",
  "Access": 12431
}
],
"(sheet)2": [
{
  "Id": 2.0,
  "Team": "Max",
  "timestamp": "2019-09-26T16:37:54",
  "Access": 81243
},
{
  "Id": 2.0,
  "Team": "Max Mule",
  "timestamp": "2019-09-26T18:00:54",
  "Access": 67676
}
]
}
Output JSON:
{
  "(sheet)1": [
    {
      "Id": 1.0,
      "Team": "Mule",
      "timestamp": "2019-09-26T16:37:54",
      "Access": 12431
    }
  ],
  "(sheet)2": [
    {
      "Id": 2.0,
      "Team": "Max",
      "timestamp": "2019-09-26T16:37:54",
      "Access": 81243
    },
    {
      "Id": 2.0,
      "Team": "Max Mule",
      "timestamp": "2019-09-26T18:00:54",
      "Access": 67676
    },
    {
      "Id": "2",
      "Access": "4444",
      "Subteam": "1"
    }
  ]
}