使用javascript在一组对象中包括字段值的总和

时间:2018-12-02 05:56:56

标签: javascript lodash

我有一个充满tasks的对象,该对象按天分组。我还希望将每个任务的time字段相加,以获取每天的总时间,并将其包括在对象中。

要从此出发:

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

对此:

{'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
}

2 个答案:

答案 0 :(得分:2)

您可以仅使用普通JS(如果需要箭头功能,则使用ES6)而无需lodash。几乎只有Array.reduceObject.entries

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 = Object.entries(obj).reduce((r,[k,v]) => {
  r[k] = ({tasks: v, totalTime: v.reduce((a,b) => (a.time || a) + b.time)})
  return r
}, {})

console.log(result)

答案 1 :(得分:1)

您可以使用lodash的_.mapValues()来迭代组,并使用_.sumBy()来获取总时间:

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>