Contact Us 1-800-596-4880

Map Object Elements as an Array

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. 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 example 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 Script:
%dw 2.0
var myInputExample = {
  "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",
        "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 application/json
---
items: myInputExample.inventory.*book map (item, index) -> {
      "theType": "book",
      "theID": index,
      "theCategory": item.category,
      "theTitle": item.title,
      "theAuthor": item.author,
      "theYear": item.year,
      "thePrice": item.price as Number
}
Output JSON:
{
  "items": [
    {
      "theType": "book",
      "theID": 0,
      "theCategory": "cooking",
      "theTitle": "Everyday Italian",
      "theAuthor": "Giada De Laurentiis",
      "theYear": "2005",
      "thePrice": 30.00
    },
    {
      "theType": "book",
      "theID": 1,
      "theCategory": "children",
      "theTitle": "Harry Potter",
      "theAuthor": "J K. Rowling",
      "theYear": "2005",
      "thePrice": 29.99
    },
    {
      "theType": "book",
      "theID": 2,
      "theCategory": "web",
      "theTitle": "Learning XML",
      "theAuthor": "Erik T. Ray",
      "theYear": "2003",
      "thePrice": 39.95
    }
  ]
}