05-11-2021 04:55 AM
Hello all,
I stumbled upon a situation where I have to find out a sum of a certain key in the objects residing in an array without reducing the objects? What I mean to say is, here is the input:
[
{
key1: value1,
key2: 10
},
{
key1: value2,
key2: 20
},
{
key1: value3,
key2: 30
}
]
The output that I am expecting should look like:
[
{
key1: value1,
key2: 10,
sum: 60
},
{
key1: value2,
key2: 20,
sum: 60
},
{
key1: value3,
key2: 30,
sum: 60
}
]
The total sum of key 2 values should be pushed into each object as a new key.
Can some one please suggest how to deal with this? Reducing won’t be the optimal solution as it would discard the objects and just add a new object with the total sum.
Thanks.
Solved! Go to Solution.
05-11-2021 04:15 PM
You can use merge function too.
Community_Example_2021_05_11.slp (3.5 KB)
$group.map(x=>x.merge({“sum”:$group.map(item => item.key2).reduce((accum, currentValue) => accum + currentValue)}))
05-12-2021 02:25 PM
Hi @Tanmay_Sarkar,
You can also use Apache Velocity within JSON Generator. Here is the script:
#set($sum = 0)
#foreach ($field in $group)
#set($sum=$sum+$field.key2)
#end
#foreach($field in $group)
#set($dummy = $field.put(“sum”,$sum))
#end
{“group”:$group}
Regards,
Bojan
05-26-2021 10:54 AM
@bojanvelevski Thanks a lot, I never realized Apache Velocity can be used within JSON generator in such a way, this would come in handy in future.
05-26-2021 10:53 AM
@skatpally Thanks a lot, this worked effortlessly.