【问题标题】:Hi I need to get the sum of all the hours. Any help please?嗨,我需要得到所有时间的总和。请问有什么帮助吗?
【发布时间】:2022-09-30 15:27:52
【问题描述】:
\"tasks\" : {
    \"details\" : [
        {
            \"task\" : \"a\",
            \"hours\" : 5,
            \"_id\" : ObjectId(\"6333fdc699f7cb3da66be656\")
        },
        {
            \"task\" : \"2\",
            \"hours\" : 5,
            \"_id\" : ObjectId(\"6335ed42115208d81dffd082\")
        },
        {
            \"task\" : \"b\",
            \"hours\" : 6,
            \"_id\" : ObjectId(\"6335ed7d115208d81dffd118\")
        }
    ]
}

我正在尝试使用 reduce 功能获得“小时数”的总数,但我无法做到这一点。既然我是javascript新手,有人可以帮忙吗?

  • 让我们看看你的reduce函数!
  • edit您的问题包括您尝试使用reduce功能,否则我们无法帮助您正确解决问题
  • 到目前为止你做了什么。

标签: javascript arrays javascript-objects


【解决方案1】:

let data ={
  "tasks" : {
      "details" : [
          {
              "task" : "a",
              "hours" : 5,
              "_id" : "6333fdc699f7cb3da66be656"
          },
          {
              "task" : "2",
              "hours" : 5,
              "_id" : "6335ed42115208d81dffd082"
          },
          {
              "task" : "b",
              "hours" : 6,
              "_id" : "6335ed7d115208d81dffd118"
          }
      ]
  }
}

let result = data.tasks.details.reduce((acc,val)=>{
  acc += val.hours
  return acc
},0)

console.log(result)

【讨论】:

    【解决方案2】:

    const tasks =  {
        "details" : [
            {
                "task" : "a",
                "hours" : 5,
                "_id" : ObjectId("6333fdc699f7cb3da66be656")
            },
            {
                "task" : "2",
                "hours" : 5,
                "_id" : ObjectId("6335ed42115208d81dffd082")
            },
            {
                "task" : "b",
                "hours" : 6,
                "_id" : ObjectId("6335ed7d115208d81dffd118")
            }
        ]
    }
    const result = tasks.details.reduce((acc, cur) => acc + +cur.hours, 0);
    console.log(result);

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-07-28
      相关资源
      最近更新 更多