Mohit Mehrotra
Mohit Mehrotra

Reputation: 301

Combining the elements of array and reformatting the output

I am having an input JSON which I would like to transform using Mule's dataweave 2.0.

Below is the input JSON.

[
   {
     "data1": {
                "role": "analyst",
                "name": "ABC"
     },
     "data2": {
                "role": "analyst",
                "name": "DEF"
     }
  },
  {
     "data1": {
                "role": "RM",
                "name": "PQRS"
     },
     "data2": {
                "role": "analyst",
                "name": "QWE"
     }
  }
]

We would like the output as below :

[
  {
     "role": "analyst",
     "name": "ABC"
  },
  {
     "role": "analyst",
     "name": "DEF"
  },
  {
     "role": "RM",
     "name": "PQRS"
  },
  {
     "role": "analyst",
     "name": "QWE"
  }
]

I have tried different options using map, pluck and flatten, but could not get the solution. Please help me with the transform function for this.

Upvotes: 0

Views: 255

Answers (2)

Shoki
Shoki

Reputation: 1538

If you want to keep the order you can:

1) Go through the elements with reduce and for each object in the array, accumulate data1 and data2

%dw 2.0
output application/json
---
payload reduce (item, acc = []) -> (acc << item.data1 << item.data2)

2) Using map, for each element in the array create an intermediate array containing data1 and data2 and then flatten that.

%dw 2.0
output application/json
---
flatten (payload map (item) -> [item.data1, item.data2])

Upvotes: 2

vikram92
vikram92

Reputation: 94

If the order of the objects in response is important:

%dw 2.0
output application/json
---
flatten (payload map (flatten $))

If the order is not important:

%dw 2.0
output application/json
---
payload.data1 ++ payload.data2

Upvotes: 0

Related Questions