Search code examples
muledataweavemule4

Extract the inner field objects and apply them to respective top level objects using Dataweave2.0


I am trying to achieve the below output from the given input. I have tried several ways of making a generic function so that when any data is passed with similar structure I get the similar output. Please help me to achieve this.

Input

[{
  "name": "Thinker",
  "details": [
      {
      "num": 1
      }, 
      {
      "num": 2
      }
   ]
}, 
{
  "name": "Blinker",
  "details": [
      {
      "num": 3
      }, 
      {
      "num": 4
      }
   ]
}]

Output

[{
  "name": "Thinker",
  "num": 1
},
{
  "name": "Thinker",
  "num": 2
},
{
  "name": "Blinker",
  "num": 3
},
{
  "name": "Blinker",
  "num": 4
}]

Solution

  • As Aled has mentioned in his comments to one of the answers, this could be another way to solve this.

    %dw 2.0
    output application/json
    ---
    payload flatMap (item,index) -> (
          item.details map {
               name: item.name,
               num:  $.num
          }
    )