Magda
Magda

Reputation: 17

How to create incremental counter in mulesoft dataweave

We have multilevel array so we are using transformation of multiple map function. In this case how to assign a field ID with incremental value.

Input:

[
  {
    "productNo": "00011111",
    "items": [
      {
        "color": "000000000006000060",
      },
      {
        "color": "000000000006000061",
      }
    ]
  },      
  {
    "productNo": "00022222",
    "items": [
      {
        "color": "000000000006000060"
      },
      {
        "color": "000000000006000061"
      }
    ]
  }
]

Dataweave code I tried for this:

%dw 2.0
output application/json
---
flatten(payload map (item, index) -> item.items map (subItem, subIndex) -> {
    "ID": subIndex,
    "PNR": item.productNo,
    "Color": subItem.color
})

Expected output:

[
  {
    "ID": 1,
    "PNR": 00011111,
    "Color": "000000000006000060"
  },
  {
    "ID": 2,
    "PNR": 00011111,
    "Color": "000000000006000061"
  },
  {
    "ID": 3,
    "PNR": 00022222,
    "Color": "000000000006000060"
  },
  { 
    "ID": 4,
    "PNR": 00022222,
    "Color": "000000000006000061"
  }
]

Above subIndex is resetting to 0 for the next iteration as per dataweave so please let me know what we can use for incremental value.

Upvotes: 0

Views: 349

Answers (1)

aled
aled

Reputation: 25812

You could convert the structure into a flat one before transforming, then insert the indexes. Example:

%dw 2.0
output application/json
---
payload flatMap ((product) -> 
    product.items map ((item) -> {PNR: product.productNo, Color: item.color} ))
    map ((item, index) -> item update {
        case .ID! -> index
    })

Output:

[
  {
    "PNR": "00011111",
    "Color": "000000000006000060",
    "ID": 0
  },
  {
    "PNR": "00011111",
    "Color": "000000000006000061",
    "ID": 1
  },
  {
    "PNR": "00022222",
    "Color": "000000000006000060",
    "ID": 2
  },
  {
    "PNR": "00022222",
    "Color": "000000000006000061",
    "ID": 3
  }
]

Upvotes: 1

Related Questions