'Access FlowVar dynamically in DataWeave

I'm trying to access a FlowVar name dynamically in DataWeave.

For example: I have a flowVars named taxInfo123. This is a linked list and my applicant.ApplicantID = 123

In my dataweave, I want to access this dynamically. Something like the following:

"TaxInfo": flowVars.'taxInfo'+applicant.ApplicantID map ((taxIdentificationDetail , indexOfTaxIdentificationDetail) -> {

This obviously doesn't work, and I'm hoping this is possible and I just need the correct syntax.



Solution 1:[1]

If you need to dynamically create the variable name, you can use the flowVars[key] syntax instead of the flowVars.key syntax. In your scenario:

"TaxInfo": flowVars[('taxInfo' ++ (flowVars.applicant.ApplicantID as :string))]

I assumed applicant was also a flowVar but you could just as easily use payload.applicant.ApplicantID or whatever your situation calls for. I also assumed it was a number so I had to cast it as a string.

When you use this syntax you want to make sure you wrap the key expression in parenthesis so it is evaluated first and then the flowVar is resolved.

So to summarize:

If you know the variable name is 'taxInfo123' -

flowVars.taxInfo123 or flowVars[taxInfo123] are both valid

If you need to create the variable name dynamically -

flowVars[(expression)]

Hope that helps!

Solution 2:[2]

Forming the variable name needs append operator like ++. Please go through the MuleSoft documentation for Dataweave operators to get better understanding of how much flexiblity is possible in Dataweave.

https://docs.mulesoft.com/mule-user-guide/v/3.8/dataweave-operators

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 j13
Solution 2 Srinivas