使用lodash动态计算嵌套集合的平均值 [英] Dynamically calculate the average for a nested collection using lodash

查看:192
本文介绍了使用lodash动态计算嵌套集合的平均值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个对象(集合)的JSON数组,例如:

I have a JSON array of objects (a collection) like:

[{
  "x": {
        "x1": 1
  },
  "y": {
    "yt": 0,
    "zt": 4,
    "qa": 3,
    "ft": 0,
    ...
  }
},
{
  "x": {
        "x1": 5
  },
  "y": {
    "yt": 10,
    "zt": 2,
    "qa": 0,
    "ft": 0,
    ...
  }
}]

我想计算每个字段的平均值.结果结构应该相同.喜欢:

I'd like to calculate average for each field. The result structure should be same. Like:

    {
      "x": {
            "x1": 3
      },
      "y": {
        "yt": 5,
        "zt": 3,
        "qa": 1.5,
        "ft": 0,
        ...
      }
    }

谢谢

推荐答案

您可以使用传播语法和lodash的_.mergeWith()合并对象. 合并时,如果第二个参数(b)是一个数字,请将其除以原始数组中的项目数,即可得出其对总平均值的贡献.如果第一个参数(a)是数字,则不加除就可以添加它(以避免多次求和),如果未定义,则加0.

You can merge the objects using the spread syntax and lodash's _.mergeWith(). When merging, if the 2nd parameter (b) is a number divide it by the number of items in the original array to get it's respective contribution to the total average. If the 1st parameter (a) is a number, just add it without dividing (to avoid dividing the sum multiple times), or add 0 if it's undefined.

我添加了2个对象数组和3个对象数组的示例.

I've added examples of 2 objects array, and 3 objects array.

const getAvg = (data) => _.mergeWith({}, ...data, (a, b) => {
  if(_.isNumber(b)) {
    return ((b || 0) / data.length) + (_.isNumber(a) ? (a || 0) : 0);
  }
});

const data1 = [
{"x":{"x1":1},"y":{"yt":0,"zt":4,"qa":3,"ft":0}},
{"x":{"x1":5},"y":{"yt":10,"zt":2,"qa":0,"ft":0}}
];

const data2 = [
{"x":{"x1":1},"y":{"yt":0,"zt":4,"qa":3,"ft":0}},
{"x":{"x1":5},"y":{"yt":10,"zt":2,"qa":0,"ft":0}},
{"x":{"x1":3},"y":{"yt":2,"zt":6,"qa":3,"ft":0}}
];

const result1 = getAvg(data1);

console.log('2 objects in the array: ', result1);

const result2 = getAvg(data2);

console.log('3 objects in the array: ', result2);

<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.4/lodash.min.js"></script>

这篇关于使用lodash动态计算嵌套集合的平均值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆