Home > Blockchain >  MuleSoft: Update the value in Array and replace the content based on condition
MuleSoft: Update the value in Array and replace the content based on condition

Time:01-13

I have below Payload. Here if points are not divisible by 5, then round up to the nearest 5. So, if the points are 250.2, the resulting number would be 250 and that is divisible by 5 so 250 would be the value returned. If the resulting value was 251.2, then the resulting whole number would be 251 and that is not divisible by 5 and would be rounded up to 155

{
  "referenceID": "1001",
  "Year": "2023",
  "Type": "BK",
  "contracts": [
    {
      "contractId": "1",
      "contractType": "Booking",
      "Points": "250.2",
      "Reservations": {
        "reservations": [
          
        ],
        "reservationPoints": ""
      }
    },
    {
      "contractId": "1",
      "contractType": "Booking",
      "Points": "251.2",
      "Reservations": {
        "reservations": [
          
        ],
        "reservationPoints": ""
      }
    }
  ]
}

Based on above conditions, output payload should be like below

{
  "referenceID": "1001",
  "Year": "2023",
  "Type": "BK",
  "contracts": [
    {
      "contractId": "1",
      "contractType": "Booking",
      "Points": "250",
      "Reservations": {
        "reservations": [
          
        ],
        "reservationPoints": ""
      }
    },
    {
      "contractId": "1",
      "contractType": "Booking",
      "Points": "255",
      "Reservations": {
        "reservations": [
          
        ],
        "reservationPoints": ""
      }
    }
  ]
}

With regards to this rounding up Points to nearest number divisible by 5, I am using below logic

if (((payload.contracts[0].Points as Number mod 5))<1) 
  (round((payload.contracts[0].Points as Number)/5)*5)
else 
  (ceil((payload.contracts[0].Points as Number)/5)*5) 

This gets the updated value based on condition but I am not able to update the Payload.

CodePudding user response:

Make use of update operator just to update Points value in the payload Object. Try like below:

%dw 2.0
output application/json
---


payload update {
    case c at .contracts -> c map ($ update{
        case p at .Points -> if((p mod 5) <1) round((p/5))*5 
        else ceil((p/5))*5
    })

}

CodePudding user response:

Based on the above suggestion, I updated payload like below

   %dw 2.0
    output application/json
    ---
    payload.contracts  map ((item,index)-> item  update {
            case Points at .Points -> if (((Points as Number mod 5))<1) (round((Points as Number)/5)*5)
             else (ceil((Points as Number)/5)*5) 
    })
  • Related