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.

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
  }
]

Your input is not a proper json. It is having a formatting error.

Try Below.

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

In this code, the index * sizeOf(item.items) calculates the base index for each outer item, and subIndex + 1 increments the index for each inner item. This way, you get a unique and incremental value for the “ID” field.

With this modification, you should get the expected output as mentioned in your example.

Leave a Comment