Is there a way to set context properties dynamically?

Hello

I am working with a flow where I have multiple identification key saved in a JSON flow variable, as in the following example:

{
  "info": {
    "id_1": {
      "previous": "value_1",
      "key_2": "value_2",
      ...
    },
    "id_2": {
    ...
    },
  ...
}

The point is that each identification key stores that sort of "previous" value, which I want to save into the flow variable, because a lot of the functionality of the flow is based on comparing new/current value to the previous value. The new/current values are retrieved using HTTP request so that the identification key is received as the response, along with the new/current value. This is why I would like to be able to set the flow variables dynamically in a loop, like:

for (var i = 0; i < responses.length; ++i) {
  var current_id = responses[i].id;
  var new_value = responses[i].new_value;
  flow.set("info[current_id]['previous']", new_value); 
}

It does not need to be done exactly like this, but I wanted to know if it is possible to set flow variables dynamically. There are no examples in the web that I found.

Thanks in advance!

The first parameter of flow.set is a string, it does not need to be a constant, it can be the value of a variable, so assuming that info[current_id]['previous'] contains a string then you want

flow.set(info[current_id]['previous'], new_value)

Note, no quotes around the variable, otherwise it will interpret the whole thing as the name of the context variable rather than using the contents of the variable.

flow.set(info[current_id]['previous'], new_value)

Is there something I am missing? If I try this I get:

"ReferenceError: info is not defined"

Should Node be able to find the correct context property without quotation marks around the first item?

Try with:

flow.set( "info['" + current_id + "']['previous']", new_value)
1 Like
flow.set( "info['" + current_id + "']['previous']", new_value)

This worked, thank you Nick!

Oh yes, I misinterpreted the requirement.

1 Like

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.