有时候后端api给的数据中,没有汇总数据,要在对象数组中找到对应属性的值去计算,网上找到2个js方法,其实是一个,写法略有差异,都是利用js的reduce遍历、计算。.
方法一:
let datalist = [
{
'skuId': 1,
'skuName': 'test1',
'number': 11
},
{
'skuId': 2,
'skuName': 'test2',
'number': 22
},
{
'skuId': 3,
'skuName': 'test3',
'number': null
},
]
let price = datalist.reduce((sum, e) => sum + Number(e.number || 0), 0)
console.log(price) // 输出33
方法二:
const countNum = (arr, keyName)=>{
let $total = 0;
$total = arr.reduce(function (total, currentValue, currentIndex, arr){
return currentValue[keyName] ? (total + currentValue[keyName]) : total;
}, 0);
return $total;
}
这两个方法我在vue.js里都分别用过。