Contact Free trial Login

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.

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"
    }
  ]
}