通过.reduce()函数访问元素

时间:2017-11-30 06:19:18

标签: javascript arrays javascript-objects arrow-functions

我试图理解.reduce()函数是如何工作的。 因此,我们有一系列购买,每次购买都是一个对象。

const purchases = [{"owner":"Barry","price":103},
{"owner":"Bob","price":75},
{"owner":"Bob","price":73},{"owner":"Barry","price":57},
{"owner":"Barry","price":128},
{"owner":"Bob","price":119},{"owner":"Barry","price":133},
{"owner":"Barry","price":27},
{"owner":"Barry","price":138},{"owner":"Bob","price":68},
{"owner":"Bob","price":50},
{"owner":"Barry","price":9},{"owner":"Bob","price":123},
{"owner":"Bob","price":135},
{"owner":"Barry","price":30},{"owner":"Barry","price":129},
{"owner":"Barry","price":38},
{"owner":"Bob","price":133},{"owner":"Barry","price":109},
{"owner":"Bob","price":115}]

我正在尝试通过.reduce()函数累积Bob的所有购买。这是我的代码:

let bobsTotal = purchases.reduce(el => {
  if (el["owner"] === "Barry") {return el["price"]}
})

我无法了解我们如何获取“价格”财产。

1 个答案:

答案 0 :(得分:4)

当您Array.prototype.reduce(function, accumulator)时:您实际上正在function内对object中的每个array进行迭代,以更新accumulator

所述function采用(accumulator, object, index, array) => (accumulator)形式。

查看Mozilla documentation reference了解详情。

请参阅下面的代码以获取实际示例。



// Purchases.
const purchases = [
  {"owner":"Barry","price":103},
  {"owner":"Bob","price":75},
  {"owner":"Bob","price":73},
  {"owner":"Barry","price":57},
  {"owner":"Barry","price":128},
  {"owner":"Bob","price":119},
  {"owner":"Barry","price":133},
  {"owner":"Barry","price":27},
  {"owner":"Barry","price":138},
  {"owner":"Bob","price":68},
  {"owner":"Bob","price":50},
  {"owner":"Barry","price":9},
  {"owner":"Bob","price":123},
  {"owner":"Bob","price":135},
  {"owner":"Barry","price":30},
  {"owner":"Barry","price":129},
  {"owner":"Barry","price":38},
  {"owner":"Bob","price":133},
  {"owner":"Barry","price":109},
  {"owner":"Bob","price":115}
]

// Total Bob.
const totalBob = purchases.reduce((total, purchase) => {    
  if (purchase.owner == 'Bob') total += purchase.price // Owner == Bob.
  return total      
}, 0)

// Log.
console.log(totalBob)