Search code examples
filtermappingmuledataweave

Filter object in an array and retain other fields in Mule4


I have 2 objects in request payload which needs to be filtered based on a field value in Mule4. Request json:

{
"Fruits": {
 "Types": [
{
 "Field1": "value1",
 "Field2": "value2",
 "Color" : {
  "Types": [
   {
    "Order": "test",
    "Cost": "22"
    },
    {
    "Order": "test1",
    "Cost": ""
    }
    ]
    }
    }
    ]
    },
    "Color" : {
  "Types": [
   {
    "Order": "test",
    "Cost": "22"
    },
    {
    "Order": "test1",
    "Cost": ""
    }
    ]
    }
    } 

In the above payload, all the fields are required but for Color.Types array, we need to filter only the object where cost != null from both Color objects above.

Expected output json:

{
    "Fruits": {
     "Types": [
    {
     "Field1": "value1",
     "Field2": "value2",
     "Color" : {
      "Types": [
       {
        "Order": "test123",
        "Cost": "44"
        }
        ]
        }
        }
        ]
        },
        "Color" : {
      "Types": [
       {
        "Order": "test",
        "Cost": "22"
        }
        ]
        }
        } 

Solution

  • Your Input and Expected Output both are different.

    Note -> There is a difference between "" (length is 0) and null (no value allocated)

    DW

    %dw 2.0
    output application/json
    import * from dw::util::Values
    ---
    payload update ["Color","Types"] with ($ filter ($.Cost != null and $.Cost != "")) update ["Fruits","Types","Color","Types"] with ($ filter ($.Cost != null and $.Cost != ""))
    

    Output

    {
      "Fruits": {
        "Types": [
          {
            "Field1": "value1",
            "Field2": "value2",
            "Color": {
              "Types": [
                {
                  "Order": "test",
                  "Cost": "22"
                }
              ]
            }
          }
        ]
      },
      "Color": {
        "Types": [
          {
            "Order": "test",
            "Cost": "22"
          }
        ]
      }
    }