Search code examples
muledataweavemule4anypoint-platform

Filter an array from Object in Dataweave


I want to check whether all the required keys are present in the input JSON and filter out those that are not present. I tried the script but I am getting the below error. How to fix this?

Input:

{"req":{
    "messageList": [
        {
            "res":1,
          
            "id":"test"
        }
    ]
}}

Required Keys:

var keys = ["res","req"]

DW Script:

%dw 2.0
output application/json
var keys = ["res"]
var p =payload.req.messageList[0]



fun getAllAbsentKeys(obj) = obj filterObject ((value, key, index) -> keys filter ((item, index) -> item == key) )
---
getAllAbsentKeys(p)

output:

["req"]


Cannot coerce Array ([]) to Boolean

Solution

  • If the intention is to get for an object what keys are missing:

    %dw 2.0
    output application/json
    import * from dw::core::Arrays
    var keys = ["res", "req"]
    var p =  [
                {
                    "res": 1
                },
                {
                    "res": 2,
                    "req": "test"
                },
                {
                    "ret": 3,
                    "id": "test"
                },
                {
                    "age": 4,
                    "req": 8,
                    "id":"test"
                }
            ]   
    
    fun missingKeys(obj, keys) = keys filter !(namesOf(obj) contains $) 
    ---
    p map missingKeys($, keys)
    

    Output:

    [
      [
        "req"
      ],
      [
        
      ],
      [
        "res",
        "req"
      ],
      [
        "res"
      ]
    ]
    

    Note that I didn't use your payload since it is not needed to explain the solution. Where the input is coming is up to you. It is better to minimize the problem and focus in its solution.