Search code examples
muleanypoint-studiodataweave

Dynamically reference payload field names in Dataweave


I am using Anypoint Studio 7.3 and Mule 4.1.

I am looking to dynamically pass the field name from a JSON payload when transforming a message so on the 1st call I want to use the values in the "cat_name" field and when I call it a 2nd time I want to use the values in the "dog_name" field as the output message structure will be the same. So for "cat_name" I would want $.(vars.codetest) to be resolved as payload.cat_name and for "dog_name" I would want $.(vars.codetest) to be resolved as payload.dog_name

Is there a way of doing this?

%dw 2.0
output application/json
---
(payload distinctBy $.#[vars.codetest]) map ((payload01, indexOfPayload) ->{
    name: $.(vars.codetest)
})

Thanks for any help


Solution

  • Something like this should work:

    %dw 2.0
    output application/json
    ---
    payload 
      distinctBy $[vars.codetest]   
      map ((element) -> { name: element[vars.codetest] })
    

    You might need parens around codeTest (i.e. (vars.codetest)) so that it gets evaluated before the lookup.