james11
james11

Reputation: 57

How to merge a child arrays based on a common field?

I have an input which has common field as an array of object, and I need to merge the object within same field. input Payload:

{
  "ID": "102B0YT0",
  "line": [
    {
      "Number": 1,
      "quantityd": 18,
      "Shipped": 15
    }
  ],
  "line": [
    {
      "Number": 2,
      "quantity": 58,
      "Shipped": 8
    },
    {
      "lineNumber": 2,
      "quantity": 59,
      "Shipped": 9
    }
  ],
  "line": [
    {
      "lineNumber": 3,
      "Ordered": 11,
      "Shipped": 17
    }
  ]
}

I'm expecting below output where all the line object will be concatenated and merged under 1 line. Desired Output:

{
  "ID": "102B0YT0",
  "line": [
    {
      "Number": 1,
      "quantityd": 18,
      "Shipped": 15
    },
    {
      "Number": 2,
      "quantity": 58,
      "Shipped": 8
    },
    {
      "lineNumber": 2,
      "quantity": 59,
      "Shipped": 9
    },
    {
      "lineNumber": 3,
      "Ordered": 11,
      "Shipped": 17
    }
  ]
}

Thank you!

Upvotes: 0

Views: 159

Answers (1)

aled
aled

Reputation: 25699

Remove the line keys from the output then add a new line key with the values of each line then flatten it. The multi value selector *.line returns an array of the values of all line keys. Because each element is an array flatten() is needed to get the value of each sub-array in a single array.

%dw 2.0
output application/json
---
payload - "line" ++  (line: flatten(payload.*line))

Upvotes: 1

Related Questions