Contact Us 1-800-596-4880

Map Object Elements as an Array

DataWeave 2.1 is compatible with Mule 4.1. Standard Support for Mule 4.1 ended on November 2, 2020, and this version of Mule will reach its End of Life on November 2, 2022, when Extended Support ends.

Deployments of new applications to CloudHub that use this version of Mule are no longer allowed. Only in-place updates to applications are permitted.

MuleSoft recommends that you upgrade to the latest version of Mule 4 that is in Standard Support so that your applications run with the latest fixes and security enhancements.

This DataWeave example uses the DataWeave map function to iterate through the object elements that match the key book. The input also includes the key magazine, which is ignored.

It uses these DataWeave functions:

  • The multi-value selector *book to return an array with the elements that match the key "book"

  • map to go through each object in the array that’s returned by the multi-value selector.

DataWeave
%dw 2.0
output application/json
---
items: payload.inventory.*book map (item, index) -> {
      "type": "book",
      "id": index,
      "category": item.category,
      "title": item.text,
      "author": item.author,
      "year": item.year,
      "price": item.price
}
Input
{
  "inventory": {
      "book" : {
        "-category": "cooking",
        "title": "Everyday Italian",
        "author": "Giada De Laurentiis",
        "year": "2005",
        "price": "30.00"
      },
      "book" :{
        "-category": "children",
        "title": "Harry Potter",
        "author": "J K. Rowling",
        "year": "2005",
        "price": "29.99"
      },
      "book" :{
        "-category": "web",
        "-cover": "paperback",
        "title": "Learning XML",
        "author": "Erik T. Ray",
        "year": "2003",
        "price": "39.95"
      },
      "magazine" :{
        "-category": "web",
        "title": "Wired Magazine",
        "edition": "03-2017",
        "price": "15.95"
      },
        "magazine" :{
        "-category": "business",
        "title": "Time Magazine",
        "edition": "04-2017",
        "price": "17.95"
      }
   }
}
Output
{
  "items": [
    {
      "type": "book",
      "id": 0,
      "category": null,
      "title": null,
      "author": "Giada De Laurentiis",
      "year": "2005",
      "price": "30.00"
    },
    {
      "type": "book",
      "id": 1,
      "category": null,
      "title": null,
      "author": "J K. Rowling",
      "year": "2005",
      "price": "29.99"
    },
    {
      "type": "book",
      "id": 2,
      "category": null,
      "title": null,
      "author": "Erik T. Ray",
      "year": "2003",
      "price": "39.95"
    }
  ]
}