0

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?

1
  • 1
    Why "with lodash"? Plain JS does this just fine, too. const valueTotal = object.Result.reduce(reducer, 0), where the reducer is something like (runningTally, currentArrayElement) => getTotalValueFrom(currentArrayElement), and I'm sure you know how to implement function getTotalValueFrom(entry). Commented Sep 26, 2020 at 20:49

1 Answer 1

3

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>

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.