anxiousAvocado
anxiousAvocado

Reputation: 187

How to get all values where a certain Key matches in Dataweave 2.0?

Payload :

[
{
    "Contacts": "123456,098765",
    "Emails" : ""
},
{
    "Contacts": "ABC123",
    "Emails" : ""
}
]

How can I get a list of all emails from the below array of objects where the contact Id matches from each row in the payload? (Expected output below)

Variable accConts

{
    "queryResponse": [
        {
            "Email": "[email protected]",
            "SalesforceId": "123456"
        },
        {
            "Email": "[email protected]",
            "SalesforceId": "098765"
            
        },
        {
            "Email": "[email protected]",
            "SalesforceId": "ABC123"
            
        }

    ]
}

Expected Output:

[
{
    "Contacts": "123456,098765",
    "Emails" : "[email protected], [email protected]"
},
{
    "Contacts": "ABC123",
    "Emails" : "[email protected]"
}
]

Upvotes: 0

Views: 1418

Answers (4)

Salim Khan
Salim Khan

Reputation: 4303

HTH..

%dw 2.0
output application/json



var qResp ={
    "queryResponse": [
        {
            "Email": "[email protected]",
            "SalesforceId": "123456"
        },
        {
            "Email": "[email protected]",
            "SalesforceId": "098765"
            
        },
        {
            "Email": "[email protected]",
            "SalesforceId": "ABC123"
            
        }

    ]
}


--- 


payload filter ($.Contacts != null) map using (iter = $$) {
    "Contacts" : $.Contacts,
    "Emails": (qResp.queryResponse filter (payload[iter].Contacts contains $.SalesforceId)) reduce ((item,acc = "") ->  (acc ++ "," ++ item.Email)[1 to -1]
    )

}


Upvotes: 1

Dale
Dale

Reputation: 1301

Wanted to add a slightly more succinct solution to show another approach.

%dw 2.0
output application/json

var qResp =
{
    "queryResponse": [
        {
            "Email": "[email protected]",
            "SalesforceId": "123456"
        },
        {
            "Email": "[email protected]",
            "SalesforceId": "098765"
            
        },
        {
            "Email": "[email protected]",
            "SalesforceId": "ABC123"
            
        }

    ]
}

--- 

payload map (value) ->
    {
        'Contacts':value.Contacts,
        'Emails': qResp.queryResponse[?(value.Contacts contains $.SalesforceId)]..Email joinBy ", "
    }

Upvotes: 0

Salim Khan
Salim Khan

Reputation: 4303

Hopefully this comaprision helps

Works fine

Results in error

Upvotes: 0

anxiousAvocado
anxiousAvocado

Reputation: 187

I accepted Salim Khan's answer as he guided me in the right direction and the logic to get emails worked. I just needed to rework the map logic,

payload map (row, index) -> {
    "Contacts" : row."Contacts",
    "Emails" : (qResp.queryResponse filter (row."Contacts" contains $.SalesforceId)) reduce ((item,acc = "") ->  (acc ++ "," ++ item.Email)[1 to -1]
    ),
}

Upvotes: 1

Related Questions