javascript - 如何搜索对象数组并获取总数
问题描述
如何搜索此对象数组并返回所有价格属性的总数
Data = [ {id:0,name:”lamp”,price: 5}
{id:1, name:”bed”, price:10}
{id:2,name: “shelf”, price 3}]
... It will need to return a total of 18
解决方案
有这种情况下经常使用Array
的方法reduce 。
它的第一个参数是一个函数,该函数将为数组中的每个元素调用,第二个但可选的参数将是初始值。
因此,在您的情况下,您可以执行以下操作:
const sum = Data.reduce((accumulator, obj) => accumulator + obj.price, 0)
第一次调用的值为accumulator
0 ,下一次累加器的值为上一次调用函数的返回值```
所以它将按以下方式工作:
// first call
// accumulator = 0
// obj = {id:0,name:”lamp”,price: 5}
return accumulator + obj.price
// second call
// accumulator = 5
// obj = {id:1, name:”bed”, price:10}
return accumulator + obj.price
// third call
// accumulator = 15
// obj = {id:2,name: “shelf”, price 3}
return accumulator + obj.price
// now accumulator = 18
推荐阅读
- sql - 如何将列值作为 Big Query 中的列标题
- javascript - 获取 javascript vanilla 中的所有先前元素
- javascript - 格式化浮点数
- continuous-integration - 在 Gitlab 管道之间传递数据
- php - 在 PHP 中删除逗号分隔字符串中的值
- c++ - 如何使用 IOCP 异步读取文件?
- kubernetes - “kubectl get pod”中的状态运行含义
“ 输出 - c# - c# 在创建窗口句柄之前,不能在控件上调用 Invoke 或 BeginInvoke System.Threading.Thread
- xamarin - 如何从 Xamarin 的 App 类中的全局变量绑定到 Codebehind
- php - 有什么方法可以
在 laravel 刀片中使用吗?