Home > Enterprise >  MuleSoft filter a json array by keys from another json array's list
MuleSoft filter a json array by keys from another json array's list

Time:02-22

In MuleSoft/DataWeave I have a json array I need to filter by key values in another json list. Here's the json I need to filter:

[
  {
    "order_by": "CDDASD",
    "product_no": "69843270432",
    "serial_number": "CD909837296",
    "place_of_origin": "SFG",
    "depot": "LK955",
    "quantity": "150"
  },
  {
    "order_by": "CDDPOI",
    "product_no": "74890327033",
    "serial_number": "CD909837297",
    "place_of_origin": "SVH",
    "depot": "MN822",
    "quantity": "900"
  },
  {
    "order_by": "CDDUYT",
    "product_no": "43720943334",
    "serial_number": "CD909837298",
    "place_of_origin": "SRF",
    "depot": "BV675",
    "quantity": "1200"
  }
]

When I make an API call I send the following json

{
  "FORMAT": [
    "order_by",
    "product_no",
    "serial_number"
  ]
}

I want the response to return only the key/value pairs in the first json that match whatever keys are specified in FORMAT. So with the above I expect a response like this:

[
      {
        "order_by": "CDDASD",
        "product_no": "69843270432",
        "serial_number": "CD909837296"
      },
      {
        "order_by": "CDDPOI",
        "product_no": "74890327033",
        "serial_number": "CD909837297"
      },
      {
        "order_by": "CDDUYT",
        "product_no": "43720943334",
        "serial_number": "CD909837298"
      }
    ]

I'm having trouble iterating through the values in FORMAT and then filtering the first json by those values. I am not even sure what functions in DataWeave I should use. Should I use map on FORMAT and then filter on the first json? I keep getting errors about using arrays when an object is expected so I am at loss. Apologies for the lack of code, I am too confused to know what I should be doing. I appreciate all help.

CodePudding user response:

Assuming your payload is always going to be what you provided (not nested structure) then you can use Map function to iterate over your payload and then filterObject to achieve your desired output

%dw 2.0
output application/json
var fields = {
  "FORMAT": [
    "order_by",
    "product_no",
    "serial_number"
  ]
}
---
payload map ((item) -> 
    item filterObject ((value, key) ->
    fields.FORMAT contains  (key as String) ))
  • Related