How to eliminate defining large set of variables in Power Automate?

Problem

Here is the scenario, let’s say that in the workflow you may need large set of variables to hold the data as a variable, and set variable with new values etc. Your first approach is to create a multiple ‘Initialize variable’ actions and wherever you make the change to the variable you will use ‘Set variable’ action.

The ‘Initialize variable’ ad ‘Set variable’ actions.

Well the problem is you will end up with lot of variables actions and it may get laborious to rename Initialize and Set actions. There is a better ways to do the same using JSON object.

Step by Step Solution

The first steps is you need to define an object with all the variables you need, e.g. the following object with variables like FirstName, LasteName, Age etc.

An object variable ‘WorkflowVarObject’ with all required variables as properties.
--- In this JSON object each variables is with the data type
--- FirstName, LastName etc. are 'String' type
--- Age is a integer type
--- Salary is float type
--- Address is an object
--- Jobs is an array

{
"FirstName": "",
"LastName": "",
"Address": {
"City":"",
"State":"",
"Zip":""
},
"Age": 0,
"Salary": 0.0,
"Jobs":[ "Job1", "Job2" ]
}

Now second step is you want to change the ‘WorkflowVarObject’ variable’s property such as FirstName, LastName etc. You can add the Set variable action with the SetProperty function.

Use SetProperty function to change the ‘FirstName’ property of the ‘WorkflowVarObject’
setProperty(variables('WorkflowVarObject'),'FirstName', 'Pankaj')

But there is a problem with above action, when you run the flow to test you will get the following error.

An error “Self reference is not supported when updating the value of variable ‘WorkflowVarObject’.”

So to workaround this first put the above expression in a compose and then set output value of the compose to set variable.

Add Compose action before setting the master JSON object variable ‘WorkflowVarObject’.

Result

The solution allowed to eliminate the multiple initialize variable actions. It allowed us to overcome an issue of the updating of the self reference.

There is a UserVoice for self reference issue if that is resolved you can eliminate the extra compose action.

About Pankaj

I am a Developer and my linked profile is https://www.linkedin.com/in/pankajsurti/
This entry was posted in Power Automate. Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s