Search code examples
javascriptangularsumlodash

Getting sum from nested array objects with Lodash?


Currenly using Angular with lodash to do some additional usability but currently hitting a roadblock.

I have the following arrays:

{
  "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,
        }
      ]
    },
  ],
}

I really need to have the Value summed up from both array objects (so I got 344).

How to achieve that with lodash?


Solution

  • With lodash, you can use nested _.sumBy() calls:

    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>