Dynamically calculate the average for a nested collection using lodash

前端 未结 4 529
予麋鹿
予麋鹿 2021-01-27 17:03

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

[{
  \"x\": {
        \"x1\": 1
  },
  \"y\": {
    \"yt\": 0,
    \"zt\": 4,
    \"qa\": 3,
    \"ft\": 0,
          


        
4条回答
  •  一整个雨季
    2021-01-27 17:22

    You could first collect and sum all values in the same data structure and then calculkate the average by a division with the length of the given array.

    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; }

提交回复
热议问题