我有一个充满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
}
答案 0 :(得分:2)
您可以仅使用普通JS(如果需要箭头功能,则使用ES6)而无需lodash。几乎只有Array.reduce
和Object.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>