首页 > 解决方案 > 如何搜索对象数组并获取总数

问题描述

如何搜索此对象数组并返回所有价格属性的总数

  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

标签: javascript

解决方案


有这种情况下经常使用Array的方法reduce 。

它的第一个参数是一个函数,该函数将为数组中的每个元素调用,第二个但可选的参数将是初始值。

因此,在您的情况下,您可以执行以下操作:

const sum = Data.reduce((accumulator, obj) => accumulator + obj.price, 0)

第一次调用的值为accumulator0 下一次累加器的值为上一次调用函数的返回值```

所以它将按以下方式工作:

// 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

推荐阅读