Search code examples
muledataweavemulesoft

DataWeave add filter inside two nested arrays


Could someone help me to create a new object using below payload data. The new object should be created using the value of field xrefValue if systemCode=="SYS2"

Payload:

{
  "objectCode": "Sampleobj",
  "masterObjectValues": [
    {
      "systemCode": "MASTER",
      "systemObjectValues": [
        {
          "codeId": "001",
          "code": "CD1",
          "crossRef": [
            {
              "systemCode": "SYS1",
              "xrefValue": "DR1"
            },
            {
              "systemCode": "SYS2",
              "xrefValue": "DR2"
            }
          ]
        },
        {
          "codeId": "002",
          "code": "CD2",
          "crossRef": [
            {
              "systemCode": "SYS1",
              "xrefValue": "MR"
            },
            {
              "systemCode": "SYS2",
              "xrefValue": "Mister"
            }
          ]
        }
      ]
    }
  ]
}

Expected Output :

[
  "DR2","Mister"
]

Solution

  • A couple of nested flatMaps to map the array levels above the key to filter, then filter and extract the value from the key you want:

    %dw 2.0
    output application/json
    ---
    payload.masterObjectValues flatMap 
        ($.systemObjectValues flatMap 
            ($.crossRef filter ($.systemCode == "SYS2")).xrefValue
        )
    

    Output:

    [
      "DR2",
      "Mister"
    ]
    

    It should work when masterObjectValues and systemObjectValues have multiple values though the example provided doesn't has them.