SG Tech Edge
SG Tech Edge

Reputation: 507

How to interate over all Postman environment variables?

In one of my pre-request script I need to have my url with all environment variables reaplced. Suddenly the env vars are injected only after the pre-request script. I want to iterate over the env variables and manually replace them. Is it possible? I can get pm.environment.values, but suddenly this object is not an array. I cant get any values from it with pm.environment.values[0] or use a for(const element of pm.environment.values) on it. If I could get all environment keys, i could acomlish my aim with pm.environment.get, but I did not found a way to do it.

Upvotes: 3

Views: 1737

Answers (1)

Danny Dainton
Danny Dainton

Reputation: 25851

You can use the .toObject() function. It returns all variables with their values, in the active environment, in a single object:

pm.environment.toObject()

https://learning.postman.com/docs/writing-scripts/script-references/postman-sandbox-api-reference/#using-environment-variables-in-scripts

This will also work for other variable scopes such as Collection, Iteration and Global.

Upvotes: 7

Related Questions