How to iterate and add a new field to an array in JSONata object?

211 views Asked by At

I have JSON object where I have a key policyList whose value type is array. Inside policyList there is another array under the key named product. There is amount field present in each object of the array product.

I want a flag inside policyList array based on the amount value i.e., if amount = '0' for all the products, then set flag to true else set flag to false.

This is the JSON I have:

{
    "admissionDate": "2023-10-04",
    "claimCaseId": 123,
    "dischargeDate": "2023-10-20",
    "hospital": "abc",
    "policyList": [
        {
            "policyNo": "P1",
            "product": [
                {
                    "amount": 1000,
                    "productName": "Product 1"
                },
                {
                    "amount": 1200,
                    "productName": "Product 2"
                }
            ]
        },
        {
            "policyNo": "P2",
            "product": [
                {
                    "amount": 0,
                    "productName": "Product 3"
                }
            ]
        }
    ],
    "reasonCode": ""
}

This is the expected JSON:

{
    "admissionDate": "2023-10-04",
    "claimCaseId": 123,
    "dischargeDate": "2023-10-20",
    "hospital": "abc",
    "policyList": [
        {
            "policyNo": "P1",
            "flag": false,
            "product": [
                {
                    "amount": 0,
                    "productName": "Product 1"
                },
                {
                    "amount": 1200,
                    "productName": "Product 2"
                }
            ]
        },
        {
            "policyNo": "P2",
            "flag": true,
            "product": [
                {
                    "amount": 0,
                    "productName": "Product 3"
                }
            ]
        }
    ],
    "reasonCode": ""
}

I tried using the Transform operator but was not able to add the evaluation logic for the flag.

2

There are 2 answers

0
mralex On BEST ANSWER

You were right to look for the Transform operator. This should solve your case:

$$ ~> |policyList|{"flag": $sum($.product.amount) = 0}|

Check it out on the Stedi Playground

0
Ross Williams On

See working playground example here

$ ~> |policyList| {'flag': product[].amount ~> $max = 0 }|