filterdataweavemulesoft

Dataweave: How to filter elements on the array from a different attribute in the same array of objects?


Could you please help me with Mulesoft dataweave script for below transformation.

Input Json:

[
  {
    "schoolName": "ABC",
    "SchoolId": "3444444",
    "AreaId": "2334555",
    "Number": "100"
  },
  {
    "schoolName": "ABC",
    "SchoolId": "77655444",
    "AreaId": "3444444",
    "Number": "100"
  },
  {
    "schoolName": "ABC",
    "SchoolId": "456666",
    "AreaId": "77655444",
    "Number": "100"
  },
  {
    "schoolName": "ABC",
    "SchoolId": "2334555",
    "AreaId": "555555",
    "Number": "100"
  }
]

Output Json: where AreaId not match with SchoolId in all JSON objects in array.

[
  {
    "schoolName": "ABC",
    "SchoolId": "23445",
    "AreaId": "555555",
    "Number": "100"
  }    
]

Solution

  • If I understood your question correctly, you are looking for elements in the payload whose AreaId does not match any other element's SchoolId.

    If that's correct, you could filter elements in your payload like this:

    %dw 2.0
    output application/json
    var allSchoolIds = payload.SchoolId
    ---
    payload filter (not (allSchoolIds contains $.AreaId))
    

    and using the input your question, your output will look like:

    [
      {
        "schoolName": "ABC",
        "SchoolId": "2334555",
        "AreaId": "555555",
        "Number": "100"
      }
    ]