简体   繁体   中英

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": "test123@test.com",
            "SalesforceId": "123456"
        },
        {
            "Email": "test@test.com",
            "SalesforceId": "098765"
            
        },
        {
            "Email": "ABC@test.com",
            "SalesforceId": "ABC123"
            
        }

    ]
}

Expected Output:

[
{
    "Contacts": "123456,098765",
    "Emails" : "test123@test.com, test@test.com"
},
{
    "Contacts": "ABC123",
    "Emails" : "ABC@test.com"
}
]

HTH..

%dw 2.0
output application/json



var qResp ={
    "queryResponse": [
        {
            "Email": "test123@test.com",
            "SalesforceId": "123456"
        },
        {
            "Email": "test@test.com",
            "SalesforceId": "098765"
            
        },
        {
            "Email": "ABC@test.com",
            "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]
    )

}


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]
    ),
}

Hopefully this comaprision helps

工作正常

结果出错

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

%dw 2.0
output application/json

var qResp =
{
    "queryResponse": [
        {
            "Email": "test123@test.com",
            "SalesforceId": "123456"
        },
        {
            "Email": "test@test.com",
            "SalesforceId": "098765"
            
        },
        {
            "Email": "ABC@test.com",
            "SalesforceId": "ABC123"
            
        }

    ]
}

--- 

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM