# How to sum together values in different objects

**URL:** <https://discuss.elastic.co/t/how-to-sum-together-values-in-different-objects/209554>\
**Category:** Logstash\
**Created:** [November 26, 2019, 5:17pm UTC](https://discuss.elastic.co/t/how-to-sum-together-values-in-different-objects/209554 "2019-11-26T17:17:31Z")\
**Posts on this page:** 4\
**Page:** 1

<div class="post-metadata">

**Author:** ![twright8](https://sea2.discourse-cdn.com/elastic/user_avatar/discuss.elastic.co/twright8/32/58294_2.png) [@twright8](https://discuss.elastic.co/u/twright8)\
**Post date:** [November 26, 2019, 5:17pm UTC](https://discuss.elastic.co/t/how-to-sum-together-values-in-different-objects/209554/1 "2019-11-26T17:17:32Z")

</div>

Hi, I have nested objects in an array. The objects are the same structure. I want to add together all [array][amount] values (which are all numbers) where x can be any number up to around 40, to create a new field [amount-sum] where this arithmetic is stored.

There is not a set amount of objects in each array and so this method does not work:

event.set( "amount-sum", event.get( "[array][0][amount]" ) + event.get( "[array][1][amount]" ) + event.get( "[array][2][amount]" ) )

Thanks,

Tom

---

<div class="post-metadata">

**Author:** ![Badger](https://sea2.discourse-cdn.com/elastic/user_avatar/discuss.elastic.co/badger/32/25190_2.png) [@Badger](https://discuss.elastic.co/u/Badger)\
**Post date:** [November 26, 2019, 5:27pm UTC](https://discuss.elastic.co/t/how-to-sum-together-values-in-different-objects/209554/2 "2019-11-26T17:27:14Z")

</div>

I haven't tested it, but you could do that in a ruby filter. Something like

```
ruby {
    code => '
        a = event.get("[array]")
        if a
            sum = 0
            a.each_index { |x|
                sum += a[x]["amount"]
            }
            event.set("amount-sum", sum)
        end
    '
}
```

---

<div class="post-metadata">

**Author:** ![twright8](https://sea2.discourse-cdn.com/elastic/user_avatar/discuss.elastic.co/twright8/32/58294_2.png) [@twright8](https://discuss.elastic.co/u/twright8)\
**Post date:** [November 26, 2019, 7:24pm UTC](https://discuss.elastic.co/t/how-to-sum-together-values-in-different-objects/209554/3 "2019-11-26T19:24:29Z")

</div>

> [@Badger](#):
>
> ruby { code =\> ' a = event.get("[array]") if a sum = 0 a.each\_index { |x| sum += a["amount"] } event.set("amount-sum", sum) end ' }

You are the best person ever, thankyou

---

<div class="post-metadata">

**Author:** ![system](https://us1.discourse-cdn.com/elastic/original/3X/1/a/1ac57faf039f6b580b3f104ef42a2a89e41014de.png) [@system](https://discuss.elastic.co/u/system)\
**Post date:** [December 24, 2019, 7:24pm UTC](https://discuss.elastic.co/t/how-to-sum-together-values-in-different-objects/209554/4 "2019-12-24T19:24:30Z")

</div>

This topic was automatically closed 28 days after the last reply. New replies are no longer allowed.
