我有这样的数据:
const data = [
{name: 'alice', colors: ['red', 'blue'], count: 1, day: '2018-11-12'},
{name: 'duke', colors: ['red', 'blue'], count: 1, day: '2018-12-12'},
{name: 'bob', colors: ['blue'], count: 1, day: '2018-11-11'},
{name: 'alice', colors: ['blue'], count: 1, day: '2018-11-10'},
{name: 'carl', colors: ['blue'], count: 3, day: '2018-11-01'},
{name: 'bob', colors: ['red'], count: 1, day: '2017-11-12'},
{name: 'bob', colors: [], count: 1, day: '2018-11-12'},
{name: 'bob', colors: ['red', 'blue', 'yellow'], count: 1, day: '2018-11-11'},
{name: 'alice', colors: ['yellow'], count: 2, day: '2018-11-11'},
{name: 'duke', colors: ['red', 'yellow'], count: 1, day: '2018-11-12'},
];
现在我想按天对数据进行分组并获取键计数的总和,以便获得这样的对象数组:
const newData = [
{day: '2018-11-12', countSum: 5}, // sum of {name: 'alice', colors: ['red', 'blue'], count: 1, day: '2018-11-12'}, {name: 'alice', colors: [blue'], count: 2, day: '2018-11-12'}, {name: 'bob', colors: [], count: 1, day: '2018-11-12'}, {name: 'duke', colors: ['red', 'yellow'], count: 1, day: '2018-11-12'}
{day: '2018-12-12', countSum: 1},
{day: '2018-11-11', countSum: 2}, // sum of {name: 'bob', colors: [blue'], count: 1, day: '2018-11-11'}, {name: 'bob', colors: ['red', 'blue', 'yellow'], count: 1, day: '2018-11-11'}
{day: '2018-11-10', countSum: 1},
{day: '2018-11-01', countSum: 3},
{day: '2017-11-12', countSum: 1},
]
我尝试使用Lodash的groupBy
按天对数据进行分组,但我无法计算count key的总和。
我需要帮助。
非常感谢
最佳答案
您可以使用Array#reduce()
创建一个以公共(public)属性值(day)为键的对象,然后使用Object.values()
返回期望的数组
const counts = data.reduce((a, {day, count}) => {
a[day] = a[day] || {day, countSum:0}
a[day].countSum += count
return a
},{})
const res = Object.values(counts)
console.log(res)
<script>
const data = [
{name: 'alice', colors: ['red', 'blue'], count: 1, day: '2018-11-12'},
{name: 'alice', colors: ['blue'], count: 2, day: '2018-11-12'},
{name: 'duke', colors: ['red', 'blue'], count: 1, day: '2018-12-12'},
{name: 'bob', colors: ['blue'], count: 1, day: '2018-11-11'},
{name: 'alice', colors: ['blue'], count: 1, day: '2018-11-10'},
{name: 'carl', colors: ['blue'], count: 3, day: '2018-11-01'},
{name: 'bob', colors: ['red'], count: 1, day: '2017-11-12'},
{name: 'bob', colors: [], count: 1, day: '2018-11-12'},
{name: 'bob', colors: ['red', 'blue', 'yellow'], count: 1, day: '2018-11-11'},
{name: 'alice', colors: ['yellow'], count: 2, day: '2018-11-11'},
{name: 'duke', colors: ['red', 'yellow'], count: 1, day: '2018-11-12'},
]
</script>
关于javascript - 按键对数据进行分组,并返回一个包含另一个键的总和值的新对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53261979/