How to calculate sum of object keys in array - javascript

前端 未结 5 1140
甜味超标
甜味超标 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:13

    You can use Javascript's reduce function. This is basically the same as @epascarello answer but in ES6 syntax.

    https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/Reduce

    const arr = [{level:2},{level:4},{level:5}]; 
    
    const total = arr.reduce((prev,next) => prev + next.level,0);
    
    console.log(total);
    

提交回复
热议问题