Home > Mobile >  Iterating Arrays Inside an Object
Iterating Arrays Inside an Object

Time:11-08

Here is the sample input JSON provided below. I am trying to iterate the 2 arrays inside the object. I am able to iterate the first array i.e ABC_TBL, However i need to get the PROG_DESC from the second array in my final payload as shown in the expected result.

sample JSON

{
    "ABC_TBL": [{
            "ORGANIZATION": "CAMBRIDGE",
            "PROG_CODE": "L9999",
            "EFFDT": "2022-01-01"

        },
        {
            "ORGANIZATION": "CAMBRIDGE",
            "PROG_CODE": "L9999",
            "EFFDT": "2023-01-01"

        }
    ],

    "XYZ_TBL": [{

            "PROG_DESC": "Artificial Intelligence",
            "RAS_ID": "",
            "CONTACT_SPOC": 0,
            "ORGANIZATION": "CAMBRIDGE",
            "EFFDT": "2022-01-01"

        },
        {

            "PROG_DESC": "Artificial Intelligence",
            "RAS_ID": "",
            "CONTACT_SPOC": 0,
            "ORGANIZATION": "CAMBRIDGE",
            "EFFDT": "2023-01-01"
        }
    ]

}

Expected Result is:

[{
        "Organization": "CAMBRIDGE",
        "Academic_program": "L9999",
        "Date_Start": "2022-01-01",
        **"description": "Artificial Intelligence"**
    },
    {
        "Organization": "CAMBRIDGE",
        "Academic_program": "L9999",
        "Date_Start": "2023-01-01",
        **"description": "Artificial Intelligence"**
    }
]

I am new to DataWeave 2.0 and Mule 4. So any help would be great.

CodePudding user response:

Assuming that you need the index of the first array to find the description on the second one, you can use the $$ default value of the map() function which contains the current index. You can use a different name if you want.

Script:

%dw 2.0
output application/json
---
payload.ABC_TBL map {
  Organization: $.ORGANIZATION,
  Academic_program: $.PROG_CODE,
  Date_Start: $.EFFDT,
  description: payload.XYZ_TBL[$$].PROG_DESC
}

Output:

[
  {
    "Organization": "CAMBRIDGE",
    "Academic_program": "L9999",
    "Date_Start": "2022-01-01",
    "description": "Artificial Intelligence"
  },
  {
    "Organization": "CAMBRIDGE",
    "Academic_program": "L9999",
    "Date_Start": "2023-01-01",
    "description": "Artificial Intelligence"
  }
]
  • Related