Search code examples
javascriptlodash

Using javascript to include sum of field values within group of objects


I have an object full of tasks that are grouped by day. I would like to also add up the time field of each task to get a total time for each day, and include that in the object.

To go from this:

{'Monday': [
  {
    task: 'Do the dishes',
    time: 15
  },
  {
    task: 'Walk the dog',
    time: 20
  }
],
'Tuesday': [
  {
    task: 'Clean house',
    time: 5
  },
  {
    task: 'Do homework',
    time: 10
  }
  ]
}

To this:

{'Monday': {
  tasks: [
    {
      task: 'Do the dishes',
      time: 15
    },
    {
      task: 'Walk the dog',
      time: 20
    }
  ],
  totalTime: 35
},
'Tuesday': {
  tasks: [
    {
      task: 'Clean house',
      time: 5
    },
    {
      task: 'Do homework',
      time: 10
    }
  ],
  totalTime: 15
}

Solution

  • You can use lodash's _.mapValues() to iterate the groups, and _.sumBy() to get the total time:

    const obj = { 'Monday': [{ task: 'Do the dishes', time: 15 }, { task: 'Walk the dog', time: 20 } ], 'Tuesday': [{ task: 'Clean house', time: 5 }, { task: 'Do homework', time: 10 } ] }
    
    const result = _.mapValues(obj, tasks => ({
      tasks,
      totalTime: _.sumBy(tasks, 'time')
    }))
    
    console.log(result)
    <script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.11/lodash.min.js"></script>