I answered a question on StackOverflow recently about creating a solution to dynamically clear out certain environment variables, that had been set during a collection run. It was something that I had done before in a manual way, by adding hard-coded string values to an array and then iterating through the list to unset each one.
I wasn’t aware of how to do this dynamically so I thought it was a great opportunity to learn something new. Whenever I’m trying to do anything in the `Tests` or `Pre-Request Script` Tabs, I will always take a quick look at the Postman Sandbox API reference page to see if there was anything that I can use – The `pm.environment.toObject()` method popped out at me, this was something that would give me the dynamic element I needed so I wouldn’t have to hard code any values within an array.
I wrote in a previous post about using the momentjs module, which is built-in to the native Postman application, to create this cleanup I’ve used another great module Lodash, this is an awesome utility module which just makes JavaScript easier by taking the hassle out of working with arrays, numbers, objects, strings, etc.
I’m using _.keys() to get a list of all the keys within the `pm.environment.toObject()` object and then using _.each() to iterate through these. To unset the variables with the “demo” prefix, I’ve added an `if` statement and used the `startsWith()` method to grab the ones I want.
For demo purposes, I’ve manually added these variables into an environment file to demonstrate what the script is doing. In a more realistic workflow, these variables would have been created during a collection run, using the `pm.environment.set()` function.
I have a mixture of variables here, some using the “demo” prefix and some without. It’s the ones with the prefix that we will be clearing out, after the request has been made.
Before the request is sent, the environment variables can seen using the environment quick look feature.
The end result of running the script, which will run after the request has been made, is that it clears out the environment variables that start with the “demo” prefix. This prefix could be changed to match one that you may use in your collections.
I’ve added a `console.log(arrItem)` statement to the code to show in the image, the keys that have been iterated through, while the script was running. When the ‘key’ matches the `if` statement condition, it’s placed into the `pm.environment.unset()` function and removed.
The code snippet can be found at the link below, please feel free to use and modify it to suit your needs. As I love to learn and my JS knowledge is still at a novice level, I’ll be happy for someone to make the code more efficient.
https://gist.github.com/DannyDainton/0a204d53e72464029a5aca8b2ae1592f
Something very quick and easy to create but hopefully others will find some benefit from using it within their own context.