I have been working on a task to calculate the total values within an array of objects structured like this:
[
{ token: 'N97235', conversions: '2', payout: '100' },
{ token: 'N91567', conversions: '2', payout: '100' },
{ token: 'N91567', conversions: '3', payout: '150' },
{ token: 'N97759', conversions: '2', payout: '100' },
{ token: 'N97240', conversions: '1', payout: '50' },
{ token: 'N13925', conversions: '1', payout: '50' },
{ token: 'N53285', conversions: '1', payout: '50' },
{ token: 'N28312', conversions: '1', payout: '100' },
{ token: 'N96475', conversions: '1', payout: '50' },
{ token: 'N97759', conversions: '2', payout: '100' },
{ token: 'N76951', conversions: '1', payout: '100' },
{ token: 'N39108', conversions: '1', payout: '50' },
{ token: 'N39108', conversions: '4', payout: '200' },
{ token: 'N48854', conversions: '2', payout: '100' },
{ token: 'N50179', conversions: '1', payout: '50' },
{ token: 'N18804', conversions: '1', payout: '50' },
{ token: 'N95631', conversions: '2', payout: '100' },
]
My goal is to sum up all the conversions and payouts in order to create a new object structured as follows
{
N97235: { conversions: 2, payout: 100 },
N39108: { conversions: 5, payout: 250 },
N91567: { conversions: 6, payout: 300},
N96475: { conversions: 1, payout: 50},
// ...and so forth
}
What I have attempted involves iterating through the array (tokens_array[] in this case) and assigning the object properties to the newly created object (the conversions_sum{}), yet I encounter issues with initializing the values before adding to them.
tokens_array.forEach(function(element) {
var token_string = element.token.toString();
if (!conversions_sum.hasOwnProperty(token_string)) {
conversions_sum[token_string] = { conversions: 0, payout: 0 };
}
conversions_sum[token_string].conversions += parseInt(element.conversions);
conversions_sum[token_string].payout += parseInt(element.payout);
});
The problem lies in not initially setting the values for conversions_sum[token_string].conversions and conversions_sum[token_string].payout, causing additions to be performed on 'undefined'.
Thank you in advance for any assistance.