When I get a response in Postman, I want to be able to set an environment variable (using
pm.environment.set("variable_key", "variable_value");
when a condition is met from the response array.
So the requirements:
set an environment variable named
idForAbc
to the value ofsomeArray.id
wheresomeArray.criteria = "ABC"
(soidForAbc = 1
)set an environment variable named
idForXyz
to the value ofsomeArray.id
wheresomeArray.criteria = "XYZ"
(soidForXyz = 2
)
Here is my sample response:
CodePudding user response:
You can choose one of 2 ways:
const res = pm.response.json();
const abc = res.someArray.find(e => e.criteria === "ABC");
if(abc){
pm.environment.set(`idFor${abc.criteria}`,abc.id)
}
const xyz = res.someArray.find(e => e.criteria === "XYZ");
if(xyz){
pm.environment.set(`idFor${xyz.criteria}`,xyz.id)
}
or
const res = pm.response.json();
function saveVarByCriteria(arr, value){
const obj = arr.find(e => e.criteria === value);
if(obj){
pm.environment.set(`idFor${obj.criteria}`, obj.id)
}
}
saveVarByCriteria(res.someArray, "ABC");
saveVarByCriteria(res.someArray, "XYZ");