gbland777 gbland777 - 1 month ago 21x
React JSX Question

How to calculate sum of object keys in array - javascript


I am working with firebase and react native.

I have returned an array from my firebase database that looks like this.

[Object, Object, Object]

Under each object I have returned a single item, "level:4".

So I have three objects containing 4,5,6. How do I sum these together?



Either a simple loop

var a = [{level:1},{level:2},{level:3},{level:4}],
    total = 0;
for (var i=0; i<a.length; i++) {
    total += a[i].level;

or reduce

var a = [{level:1},{level:2},{level:3},{level:4}],
    total = a.reduce( function(cnt,o){ return cnt + o.level; }, 0);