How can we iterate and change an array inplace in an object in JSONata?

95 views Asked by At

I have an JSON obect where I have an key policyList whose value type is array. Inside policyList there is another array under the key named product.

Here I want to change the value of amount which is inside each object of the array product.

I am able to change it but in the end I am getting only the array of amount where as I want the whole orignal object which modified amount values.

Please refer to this link for the data in JSONata Exerciser link where I have the data and the expression I have written.

JSON:

{
  "admissionDate": "2023-10-04",
  "claimCaseId": 123,
  "claimCaseStatusDescp": "Waiting",
  "claimTypeDescp": "Hospitalization",
  "dischargeDate": "2023-10-20",
  "hospital": "abc",
  "policyList": [
    {
      "policyNo": "P1",
      "product": [
        {
          "amount": 10243,
          "claimDecision": "7",
          "claimDecisionDescp": "Pending",
          "productName": "Auto"
        },
        {
          "amount": 1023,
          "claimDecision": "7",
          "claimDecisionDescp": "Pending",
          "productName": "Mob"
        },
        {
          "amount": 100000,
          "claimDecision": "8",
          "claimDecisionDescp": "Approved",
          "productName": "PA"
        }
      ]
    }
  ],
  "reasonCode": ""
}

The expression I have written is:

$map($.policyList.product.amount, function($amount) {
    $formatNumber($amount,'#,###')
})

The output coming is:

[
  "10,243",
  "1,023",
  "100,000"
]

The expected output is:

{
  "admissionDate": "2023-10-04",
  "claimCaseId": 123,
  "claimCaseStatusDescp": "Waiting",
  "claimTypeDescp": "Hospitalization",
  "dischargeDate": "2023-10-20",
  "hospital": "abc",
  "policyList": [
    {
      "policyNo": "P1",
      "product": [
        {
          "amount": "10,243",
          "claimDecision": "7",
          "claimDecisionDescp": "Pending",
          "productName": "Auto"
        },
        {
          "amount": "1,023",
          "claimDecision": "7",
          "claimDecisionDescp": "Pending",
          "productName": "Mob"
        },
        {
          "amount": "100,000",
          "claimDecision": "8",
          "claimDecisionDescp": "Approved",
          "productName": "PA"
        }
      ]
    }
  ],
  "reasonCode": ""
}

NOTE: In the expected output I have shown amount as a string but I am okay with any data type there, given that my operations on the value is present in the output in place

1

There are 1 answers

1
mralex On BEST ANSWER

To update a nested object in place, you can use the Transform operator:

$$ ~> |policyList.product|{"amount": $formatNumber(amount,'#,###')}|

Check it out live on Stedi Playground.