Lodash是一个流行的JavaScript工具库,提供了许多实用的函数来简化开发过程。在对象数组中使用多个groupBy和sumBy可以通过Lodash的groupBy和sumBy函数来实现。
示例代码:
const _ = require('lodash');
const data = [
{ name: 'Alice', age: 25, gender: 'female' },
{ name: 'Bob', age: 30, gender: 'male' },
{ name: 'Charlie', age: 35, gender: 'male' },
{ name: 'David', age: 40, gender: 'male' },
{ name: 'Eve', age: 45, gender: 'female' }
];
const groupedData = _.groupBy(data, 'gender');
console.log(groupedData);
输出结果:
{
female: [
{ name: 'Alice', age: 25, gender: 'female' },
{ name: 'Eve', age: 45, gender: 'female' }
],
male: [
{ name: 'Bob', age: 30, gender: 'male' },
{ name: 'Charlie', age: 35, gender: 'male' },
{ name: 'David', age: 40, gender: 'male' }
]
}
示例代码:
const _ = require('lodash');
const data = [
{ name: 'Alice', age: 25, gender: 'female' },
{ name: 'Bob', age: 30, gender: 'male' },
{ name: 'Charlie', age: 35, gender: 'male' },
{ name: 'David', age: 40, gender: 'male' },
{ name: 'Eve', age: 45, gender: 'female' }
];
const totalAge = _.sumBy(data, 'age');
console.log(totalAge);
输出结果:
175
综合应用: 可以结合groupBy和sumBy函数,实现在对象数组中使用多个groupBy和sumBy的功能。例如,我们可以根据性别分组,并计算每个性别的年龄总和。
示例代码:
const _ = require('lodash');
const data = [
{ name: 'Alice', age: 25, gender: 'female' },
{ name: 'Bob', age: 30, gender: 'male' },
{ name: 'Charlie', age: 35, gender: 'male' },
{ name: 'David', age: 40, gender: 'male' },
{ name: 'Eve', age: 45, gender: 'female' }
];
const groupedData = _.groupBy(data, 'gender');
const result = {};
_.forEach(groupedData, (group, key) => {
result[key] = _.sumBy(group, 'age');
});
console.log(result);
输出结果:
{
female: 70,
male: 105
}
推荐的腾讯云相关产品和产品介绍链接地址:
领取专属 10元无门槛券
手把手带您无忧上云