Search code examples
salesforcemuledataweavemulesoftmule4

Iterate through the array and generate a new variable for each element


I have a JSON array stored in a variable which looks like below

{
  "Opportunity": {
    "QuoteLineItems": {
      "QuoteLineItem": {
        "ServiceTypeCode": "CC",
        "PhaseLevel": "1",
        "Quantity": "1",
        "UnitPrice": "2,854.50",
        "InvoicedSinceLast": "0.00",
        "LevelItems": {
          "LevelItem": {
            "PhaseLevelItemNumber": "R072",
            "DocumentNotes": {
              "Note": null
            }
          }
        },
        "Colonies": {
          "ColonyStage": {
            "QuoteColonyLineNumber": "1",
            "StageItems": {
              "StageItem": {
                "StageLineProperty": "CHARGE",
                "StageQuoteItemNumber": "ICM_033",
                "DocumentNotes": {
                  "Note": null
                }
              }
              }
            }
          }
        }
      },
      "QuoteLineItem": {

I need to iterate through each of the QuoteLineItem and generate a new json variable for each Item so I am using the For each element like below

enter image description here

Inside the For each I am having a transform Messgae to generate a new json like below

%dw 2.0
output application/json
---
{
   "productCode" : //Not sure how to access the ServiceTypeCode on the QuoteLineItem 
   "axSequenceNumber" : vars.counter,
}

How do I get the ServiceTypeCode for each QuoteLineItem in the transform message inside the for each loop. I a new to Mulesoft and any help is greatly appreciated


Solution

  • QuoteLineItem is an object, not an array, so you can't use it to iterate. Instead you can use the multi-value selector to retrieve all matching keys as an array and use that to iterate:

      <foreach doc:name="For Each" collection="#[payload.Opportunity.QuoteLineItems.*QuoteLineItem]">
    

    Inside the foreach you receive each element of the input array as the payload:

    %dw 2.0
    output application/json
    ---
    {
       "productCode" : payload.ServiceTypeCode
       "axSequenceNumber" : vars.counter
    }
    

    I'm not sure what you are trying to achieve exactly by storing that into a variable. You should consider if a single transform may not achieve the same results.