使用lodash动态计算嵌套集合的平均值

时间:2017-05-11 19:41:57

标签: javascript json lodash

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

[{
  "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": 5,
        "zt": 3,
        "qa": 1.5,
        "ft": 0,
        ...
      }
    }

由于

4 个答案:

答案 0 :(得分:2)

您可以使用展开语法和lodash的192.168.0.182合并对象。 合并时,如果第二个参数(b)是一个数字除以原始数组中的项目数,以得到它对总平均值的相应贡献。如果第一个参数(a)是一个数字,只需添加它而不分割(以避免多次除以和),或者如果它未定义则加0。

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

_.mergeWith()
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);

答案 1 :(得分:0)

您可以先收集并汇总同一数据结构中的所有值,然后按照给定数组长度的除法计算平均值。



function getParts(array, result) {
    function iter(o, r) {
        Object.keys(o).forEach(function (k) {
            if (o[k] && typeof o[k] === 'object') {
                return iter(o[k], r[k] = r[k] || {});
            }
            r[k] = (r[k] || 0) + o[k];
        });
    }

    function avr(o) {
        Object.keys(o).forEach(function (k) {
            if (o[k] && typeof o[k] === 'object') {
                return avr(o[k]);
            }
            o[k] = o[k] /data.length;
        });
    }

    data.forEach(function (a) {
        iter(a, result);
    });
    avr(result);
}

var data = [{ x: { x1: 1 }, y: { yt: 0, zt: 4, qa: 3, ft: 0, } }, { x: { x1: 5 }, y: { yt: 10, zt: 2, qa: 0, ft: 0, } }],
    result = {};

getParts(data, result);

console.log(result);

.as-console-wrapper { max-height: 100% !important; top: 0; }




答案 2 :(得分:0)



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

function findAverage(array) {
  
  let counter = {},
    result = {},
    i,
    obj,
    key,
    subKey;
  
  // Iterate through array
  for (i = 0; i < array.length; i++) {
    obj = array[i];
    // Copy each key in array element to counter object
    for (key in obj) {
      counter[key] = counter[key] || {};
      // Increment and keep count of key-values of counter based on values in array element
      for (subKey in obj[key]) {
        counter[key][subKey] = counter[key][subKey] || {total: 0, numElements: 0};
        counter[key][subKey].total += obj[key][subKey];
        counter[key][subKey].numElements += 1;
      }
    }
  }
  // Go back through counter to find average of all existing subkeys (based on incremented total and the number of elements recorded) and throw it into result object
  for (key in counter) {
    result[key] = result[key] || {};
    
    for (subKey in counter[key]) {
      result[key][subKey] = counter[key][subKey].total / counter[key][subKey].numElements;
    }
  }
  
  return result;
}

console.log(findAverage(objectArray));
&#13;
&#13;
&#13;

不是绝对优化的,复制对象可以递归完成而无需事先知道它们的结构,但我希望尽可能保持步骤。

已修改为允许测试为代码段。不知道你甚至可以在SO上做到这一点!

答案 3 :(得分:0)

var array = [{
  "x": {
        "x1": 1
  },
  "y": {
    "yt": 0,
    "zt": 4,
    "qa": 3,
    "ft": 0
  }
},
{
  "x": {
        "x1": 5
  },
  "y": {
    "yt": 10,
    "zt": 2,
    "qa": 0,
    "ft": 0
  }
}];
function aintob(){
  var o = {};
  var first = array[0],
      second = array[1];
  var result = {x:{},y:{}};
  var each = function(letter, oa, ob){
    var i,
    letter = {};
    for(i in oa){
      letter[i] = (oa[i]+ob[i])/2;
    }
    return letter;
  }
  o.x = each("x", first.x, second.x);
  o.y = each("y", first.y, second.y);
  return o;
}
console.log(aintob());