Sum of collection variables

So, I have a few variable set in a collection that are numbers:

Screenshot 2023-04-12 at 5.03.00 PM

And I’m looking to run a call that adds these variables up, and sets the sum of them as “alltotal”.

I’ve tried things like:

let allcount = +sub1total + +sub2total (etc.) – I get an error stating sub1total isn’t set.

I’ve tried to parse these into integers using:
console.log(parseInt(pm.environment.get(“sub1total”)) + parseInt(pm.environment.get(“sub2total”))) – get the same error.

Not sure where to go.

Hi @brcox9090

You could do something like:

//Get all vars from environment
let subsub1 = parseInt(pm.environment.get('subsub1'));
let sub1total = parseInt(pm.environment.get('sub1total'));
let subsub2 = parseInt(pm.environment.get('subsub2'));
let sub2total = parseInt(pm.environment.get('sub2total'));
let sub3total = parseInt(pm.environment.get('sub3total'));
let sub22 = parseInt(pm.environment.get('sub22'));

//add them
let alltotal = subsub1 + sub1total + subsub2 + sub2total + sub3total + sub22;

//output to console and send total to environment
console.log(alltotal);
pm.environment.set('alltotal', alltotal)

Output:
image

image

This could work too but it’s only going to work if the only thing you have in your environment file is a set of variables that have numbers:

let obj = pm.environment.toObject(),
    sumValues = obj => Object.values(obj).reduce((a, b) => parseInt(a) + parseInt(b), 0);

pm.environment.set('sumTotal', sumValues(obj))

I totally stole this from a question on SO :smiley:

1 Like

Thank you for the response! This got me the expected return. Getting better with this stuff thanks to these answers so I really appreciate it!