-1

我正在循环一组输入。我需要统计分组总数。

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

我将如何检查以确保我没有重复 - 并且我可以计算结果?

4

5 回答 5

0

您可以执行以下操作:

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

看到这个工作演示

于 2013-09-02T13:11:40.310 回答
0
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)
});

在输出变量处查找输出。

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

于 2013-09-02T12:13:25.397 回答
0

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

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

});

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

于 2013-09-02T11:54:20.330 回答
0

您可以使用 for 循环遍历对象。如果要删除项目,只需将其设置为 null。

例子:

for(var i in compoundedArray){
    for(var j in compoundedArray){
        if(i == j){
            compoundedArray[i] += compoundedArray[j];
            compoundedArray[j] = null;
        }
    }
}
于 2013-09-02T11:29:42.157 回答
0

这行得通。它是纯 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]
    }
};
于 2013-09-02T12:24:40.107 回答