将结果组合到一个对象中

Combining results into one object

本文关键字:一个对象 组合 结果      更新时间: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 array = [
    "matching": 50,
    "growth": 20    
]   
var array = [
    "matching": 50,
    "growth": 20    
] 

不是有效的JS,但您可以创建形式的对象

var obj = {
    "matching": 50,
    "growth": 20
};

这很容易做到,只需从一开始就使用一个对象:

var result = {};
holder.find(".dataset input").each(function(index) {
    var val = +$(this).val(); // use unary plus to convert to number
    var dataType = $(this).data("type");
    result[dataType] = (result[dataType] || 0) + val;
});

进一步阅读材料:

  • MDN-使用对象
  • Eloquent JavaScript-数据结构:对象和数组

您可以只使用具有唯一键的对象(而不是数组)。

var compoundedObj = {};
$(".dataset input", holder).each(function() {
    var dataType = $(this).data("type");
    if(!compoundedObj.hasOwnProperty(dataType)) {
        compoundedObj[dataType] = 0;
    }
    compoundedObj[dataType] += parseInt($(this).val(), 10);
});

通过这种方式,你会得到这样一个对象:

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

实时演示

http://jsfiddle.net/GFwGU/

var original = [{"growth":30},{"growth": 40},{"other": 20}]
// object to sum all parts by key
var sums = {}
// loop through original object
for(var index in original){
    // get reference to array value (target object)
    var outer = original[index]
    // loop through keys of target object
    for(var key in outer){
        // get a reference to the value
        var value = outer[key]
        // set or add to the value on the sums object
        sums[key] = sums[key] ? sums[key] + value : value
    }
}
// create the output array
var updated = []
// loop through all the summed keys
for(var key in sums){
    // get reference to value
    var value = sums[key]
    // create empty object
    var dummy = {}
    // build object into desired format
    dummy[key] = value
    // push to output array
    updated.push(dummy)
}
// check the results
alert(JSON.stringify( updated ))
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)
});