Nav

Example: Map Object Elements as an Array

This example uses the DataWeave map function to iterate through the object elements that match the key book. The input also includes magazines, that are 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

         
      
1
2
3
4
5
6
7
8
9
10
11
12
%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

         
      
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
{
  "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

         
      
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
{
  "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"
    }
  ]
}

In this topic: