Reputation: 95
I want to do something really simple. I want to find the total sum of all the elements of a JSON object via openwhisk and javascript. However, the following code gives 0 as a result.
function sum(params){
var s=0;
for(var i=0; i<params.length; i++) s+=params[i];
return s;
}
function main(params){
return {payload : sum(params)};
}
As an input I have for instance this {0: 2, 1: 56, 2: 99, 3:12}
Any suggestions?
Upvotes: 1
Views: 67
Reputation: 24174
{0: 2, 1: 56, 2: 99, 3:12}
this is object so, params.length
is not valid.
Try the array input:
[2, 56, 99, 12]
Otherwise, loop through the object:
function sum(params){
var s=0;
for(var key in params) {
if (params.hasOwnProperty(key)) {
s += parseInt(params[key]);
}
}
return s;
}
function main(params){
return {payload : sum(params)};
// params = {0: 2, 1: 56, 2: 99, 3:12}
}
Upvotes: 2
Reputation: 3120
More of a JavaScript than an OpenWhisk question, but here you go:
function sum(params) {
return Object.values(params).reduce((acc, cur) => acc + cur);
}
function main(params) {
return {payload: sum(params)};
}
Object.values(obj)
returns an array of all values in the object. reduce
aggregates all values of an array into a single value using the aggregation function (acc + cur
in this case)
Upvotes: 3