How to calculate sum of object keys in array - javascript

前端 未结 5 1143
甜味超标
甜味超标 2021-02-09 11:50

Question

I am working with firebase and react native.

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

[Object, Object,         


        
5条回答
  •  情歌与酒
    2021-02-09 12:30

    Use Array.prototype.forEach() method to iterate over your array and sum your elements.

    Let us suppose your array is var foo = [object, object, object] Each object has this structure, { level : 4 }

    Write code like this:

    var sum = 0;
    foo.forEach(function(obj){
      sum += obj.level;
    });
    

    sum will store the sum

提交回复
热议问题