如何使用Lodash对对象数组按年份执行指定运算输出目标结果
实现方案
Lodash没有提供单函数直接完成这个聚合计算场景,但可以通过几个内置工具函数链式调用实现,逻辑清晰也不需要手写遍历兜底:
- 第一步:提取数组里所有对象的不重复年份键,避免漏算、错算字段
- 第二步:遍历每个年份键,按数组顺序取出4个元素对应该年份的值,对应
input1到input4 - 第三步:代入公式
(input1 + input2 - input3) / input4计算结果,组装成要求的[年份, 计算值]二维数组格式
代码实现
import _ from 'lodash' const sourceData = [ { '2002': 2, '2003': 1, '2004': 5 }, { '2002': 2, '2003': 5, '2004': 2 }, { '2002': 3, '2003': 2, '2004': 3 }, { '2002': 5, '2003': 4, '2004': 4 } ] const calcResult = _.chain(sourceData) .flatMap(_.keys) .uniq() .map(yearKey => { const [input1, input2, input3, input4] = _.map(sourceData, yearKey) // 如果需要年份为数字类型就加Number转换,要字符串类型直接传yearKey即可 return [Number(yearKey), (input1 + input2 - input3) / input4] }) .value() // 输出结果:[ [ 2002, 0.2 ], [ 2003, 1 ], [ 2004, 1 ] ] console.log(calcResult)
边界兜底优化
如果你的数据源可能存在对象缺字段、数组长度不足4的情况,可以在取值时加默认值兜底,避免计算出NaN:
const [input1 = 0, input2 = 0, input3 = 0, input4 = 1] = _.map(sourceData, item => _.get(item, yearKey, 0))
内容的提问来源于stack exchange,提问作者alik
相关产品推荐
相关产品推荐

