Reference variable in a variable?

Options

Hi,

I'm using a loop to manipulate an object. I need each loop to use a succesive element in my JSON data. For example:

Loop 0 —> user.preference.0

Loop 1 —> user.preference.1

Loop 2 —> user.preference.2

Initially I thought I could simply use the loop's "index" variable (which tracks the loop's current iteration number) in my JSON variable, such as user.preference.index. But I quickly realized that it's not possible to use a variable in another variable. (At least not like that.)

How can I reference a variable in another variable, is it possible? If not, is there another option that can allow me to increment my JSON data variable for each loop as described above?

Thank you!

Comments

  • Chris Coleman
    Chris Coleman Administrator

    ADMIN

    Options

    Hi, @mikhaeel! You can use the loop's index if you're using a For Loop, as it maintains the index variable automatically. To do so in your example, you'd reference 'user.preference' and then apply a GET filter, with the path being the index variable.

    If this is a For Each loop, you can establish a 'count' variable outside of the loop with a value of -1, and add 1 to it as the first step of the loop so it starts at 0, and this will match the index of the array which you can use as described above.

    Let me know if that makes sense.

  • mikhaeel
    mikhaeel Member
    Options

    Hey @Chris Coleman, thanks for your reply.

    Aha, yes I forget about using the GET filter instead of dot notation. And I suppose if I need to substitute a variable in the middle of a text path I could use the GET filter and sprintf?

    Thanks!

  • Chris Coleman
    Chris Coleman Administrator

    ADMIN

    Options

    Yep! The path parameter in GET is just text, so you can do any sort of manipulation or replacement you'd like there.

  • mikhaeel
    mikhaeel Member
    Options

    Great, thanks for your help @Chris Coleman!

  • AgIQ
    AgIQ Member
    Options

    Hi @mikhaeel , would you mind sharing a screenshot of your solution. I just can get the variable in the path (dot notation) to accept the new value. Thanks!

  • AgIQ
    AgIQ Member
    Options

    @mikhaeel No worries. I figured it out.