如何将一个结果列表合并到一个包含汇总的压缩对象中

How do I merge a list of results into a compacted object with totals

本文关键字:一个 压缩 包含汇 对象 结果 列表 合并      更新时间:2023-09-26

我正在循环一组输入。我需要把分组的总数加起来。

var compoundedArray = new Array();
    holder.find(".dataset input").each(function(index) {
        var val = $(this).val();
        var dataType = $(this).data("type");
        var localObj = {};
        localObj[dataType] = val;
        compoundedArray.push(localObj);
    });

我有一个像这样的物体

[
    {
    "growth":30
    },
    {
    "growth": 40
    },
    {
    "other": 20
    }
]

如何循环遍历对象以生成类似的东西

[
    {
        "growth": 70
    },
    {
        "other": 20
    }
]

如果我在初始数组对象上循环

for (var i = 0; i < compoundedArray.length; i++) {
console.log(compoundedArray[i]);
}

我该如何进行检查以确保我没有重复项,并且我可以统计结果?

我认为您对数据结构的选择有点太复杂了。试试类似的东西。

var compoundedObject = {};
holder.find(".dataset input").each(function(index) {
    var val = $(this).val();
    var dataType = $(this).data("type");
    //Assuming all values are integers and can be summed:
    if( compoundedObject.hasOwnProperty(dataType) )
    { 
        compoundedObject[dataType] += val;
    }
    else
    {
        compoundedObject[dataType] = val;
    }
});

您最终会得到一个对象,而不是一个数组。

var add=function (a,b){ a=a||0; b=b||0; return a+b};
var input=[ {growth:30},{growth:40},{other:20} ],output=[],temp={};

$.each(input,function(i,o){
  var n;
  for(i in o)
     {n=i;break}
  temp[n]=add(temp[n],o[n]);
});
$.each(temp,function(i,o){
  var k={};
   k[i]=o;
  output.push(k)
});

在输出变量处查找输出。

不要发布太多具体的问题,这可能对其他人没有帮助。

这很有效。它是纯javascript。

var totals = {};
for (var i = 0; i < compoundedArray.length; i++) {
    var item = compoundedArray[i];
    for (var key in item) {
        totals[key] = (totals[key] || 0) + item[key]
    }
};

您可以使用for循环通过对象进行循环。如果您想删除一个项目,只需将其设置为null即可。

示例:

for(var i in compoundedArray){
    for(var j in compoundedArray){
        if(i == j){
            compoundedArray[i] += compoundedArray[j];
            compoundedArray[j] = null;
        }
    }
}

您可以执行以下操作:

var totals = [], tmp = {};
for (var i = 0; i < compoundedArray.length; i++) {
    var obj = compoundedArray[i];
    for (var j in obj) {
        tmp[j] = tmp[j] || 0;
        tmp[j] += obj[j];
    }
}
for(var k in tmp) {
    var obj = {};
    obj[k] = tmp[k];
    totals.push(obj);
}

请参阅此工作演示