【问题标题】:Getting sum from nested array objects with Lodash?使用 Lodash 从嵌套数组对象中获取总和?
【发布时间】:2020-09-26 20:46:23
【问题描述】:

目前使用 Angular 和 lodash 来实现一些额外的可用性,但目前遇到了障碍。

我有以下数组:

{
  "Result": [
    {
      "Name": "marketeerBoston",
      "Label": "Week25",
      "Total": 251200,
      "Specific": [
        {
          "Label": "3",
          "Value": 25,
        },
        {
          "Label": "4",
          "Value": 250,
        }
      ]
    },
    {
      "Name": "marketeerJersey",
      "Label": "Week25",
      "Total": 776090,
      "Specific": [
        {
          "Label": "1",
          "Value": 32,
        },
        {
          "Label": "2",
          "Value": 37,
        }
      ]
    },
  ],
}

我真的需要从两个数组对象中总结出Value(所以我得到了 344)。

如何使用 lodash 来实现?

【问题讨论】:

  • 为什么要使用 lodash? Plain JS 也可以做到这一点。 const valueTotal = object.Result.reduce(reducer, 0),reducer 类似于(runningTally, currentArrayElement) => getTotalValueFrom(currentArrayElement),我相信你知道如何实现function getTotalValueFrom(entry)

标签: javascript angular sum lodash


【解决方案1】:

使用 lodash,您可以使用嵌套的 _.sumBy() 调用:

const data = {"Result":[{"Name":"marketeerBoston","Label":"Week25","Total":251200,"Specific":[{"Label":"3","Value":25},{"Label":"4","Value":250}]},{"Name":"marketeerJersey","Label":"Week25","Total":776090,"Specific":[{"Label":"1","Value":32},{"Label":"2","Value":37}]}]}

const result = _.sumBy(data.Result, obj => _.sumBy(obj.Specific, 'Value'))

console.log(result)
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.20/lodash.min.js" integrity="sha512-90vH1Z83AJY9DmlWa8WkjkV79yfS2n2Oxhsi2dZbIv0nC4E6m5AbH8Nh156kkM7JePmqD6tcZsfad1ueoaovww==" crossorigin="anonymous"></script>

【讨论】:

    猜你喜欢
    • 2021-07-21
    • 1970-01-01
    • 1970-01-01
    • 2018-07-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-05-15
    • 1970-01-01
    相关资源
    最近更新 更多