美文网首页
JS 计算对象数组中某个属性合计

JS 计算对象数组中某个属性合计

作者: 深渊凝视 | 来源:发表于2023-06-12 09:53 被阅读0次

countTotal调用示例:

  • 模板数组
let arr = [
    {id: 0, price: 199.88},
    {id: 1, price: 299.88},
    {id: 2, price: 399.88}
];
console.log(countTotal(arr, 'price')); //899.64
  • 计算函数
//计算对象数组中某个属性合计
function countTotal(arr, keyName) {
    let $total = 0;
    $total = arr.reduce(function (total, currentValue, currentIndex, arr){
        return currentValue[keyName] ? (total + currentValue[keyName]) : total;
    }, 0);
    return $total;
}

相关文章

网友评论

      本文标题:JS 计算对象数组中某个属性合计

      本文链接:https://www.haomeiwen.com/subject/mfzfydtx.html