Contact Us 1-800-596-4880

Merge Multiple Payloads

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 deals with an input that contains a collection of collections. The first payload index payload[0] lists price by book, and the second payload[1] lists authors by book, where each book can be identified by a unique bookId key. This transformation merges both payload array elements into one, matching their keys, where one book may have several authors.

Note that this is not the same as having as an input a single payload that consists of an array. Here, payload is an array of arrays.

It uses these functions:

  • map goes through the elements of the first payload element (payload[0]). While on each element, a second map function goes through the elements of the second payload (payload[1]) that match the filter criteria.

  • using defines a shorter alias within the scope of the main map function.

  • filter limits the scope of the second map function to only objects that share the same bookId as is currently being processed by the first map function. In that way, only relevant authors for each are listed in the output.

DataWeave
%dw 2.0
output application/json
---

payload[0]  map (bookListing) -> using (id = bookListing.bookId) {
	bookId:	id,
    title:  bookListing.title,
	price: 	bookListing.price as Number,
	(payload[1] filter ($.*bookId contains id)  map (bookAuthor) -> {
		author:bookAuthor.author
   })
}
Input 1 for Collection - Payload[0]
[
  { "bookId":"101",
    "title":"world history",
    "price":"19.99"
  },
  {
    "bookId":"202",
    "title":"the great outdoors",
    "price":"15.99"
  }
]
Input 2 for Collection - Payload[1]
[
  {
    "bookId":"101",
    "author":"john doe"
  },
  {
    "bookId":"202",
    "author":"jane doe"
  }
]
Output
[
  {
    "bookId": "101",
    "title": "world history",
    "year": "2017",
    "isbn": "11111",
    "price": "19.99",
    "author": "john doe"
  },
  {
    "bookId": "202",
    "title": "the great outdoors",
    "year": "2016",
    "isbn": "22222",
    "price": "15.99",
    "author": "jane doe"
  }
]