0

I am trying to parse the response data and getting the values for the "id". Since I am expecting multiple values for the same response I am putting it into an array. Inside a for loop I increment the array with the index set to i. Each of these values i need to pass it to a global variable like var_id0, var_id1... var_idn.

Can the numeric against the global name "var_id" be incremented inside the for loop?

I looked up multiple examples but none are showing me if such a thing can be done when setting the global variable.

var index_id= [];
var jsonData = JSON.parse(responseBody);
for (var i = 0; i < jsonData.list.length; i++) {  
    var counter = jsonData.list[i];
    index_id[i] = counter.id;
    pm.globals.set("var_id"[i], index_id[i]) <<-- How can this be achieved.
    //pm.globals.set("variable name", "variable value") --> Actual syntax.
}

My expectation is that till the end of the for loop is reached, with each loop the global variable name, will be incremented by 1 and the corresponding value will be set. For eg:

var_id1 = "700" var_id2 = "800"...

4 Answers4

2

"var_id"[i] means look up the ith index in "var_id", and for strings that will evaluate to the character at position i, so "var_id"[0] would be "v". Instead, you want to build up strings by appending i to "var_id", that can be done with +.

Jonas Wilms
  • 132,000
  • 20
  • 149
  • 151
  • 1
    Hi Jonas Wilms, that worked like a charm. Thank you. By adding a +, as you mentioned, it helps add a numeric against the global variable name. Thank you. – Kiran Cherian Jul 09 '19 at 12:25
1

Change

pm.globals.set("var_id"[i], index_id[i])

To

pm.globals.set(`var_id${i}`, index_id[i])
xchrisbradley
  • 416
  • 6
  • 21
1

Why do you need all this global variables? Define one global array and push your values into it. Then access them by index. Almost the same syntax as you wanted.

Polina F.
  • 629
  • 13
  • 32
-3

You can use eval function.

var index_id= [];
var jsonData = JSON.parse(responseBody);
for (var i = 0; i < jsonData.list.length; i++) {  
    var counter = jsonData.list[i];
    index_id[i] = counter.id;
    eval("var_id"+i+"="+index_id[i]);
    //pm.globals.set("var_id"[i], index_id[i]) <<-- How can this be achieved.
    //pm.globals.set("variable name", "variable value") --> Actual syntax.
}
yılmaz
  • 1,818
  • 13
  • 15