遍历对象数组并根据条件添加到其他数组

时间:2017-08-02 15:25:25

标签: javascript arrays object

我有一个包含以下对象的数组。

var notTotal = [{"Year":2012,"Value":800579},
                {"Year":2012,"Value":654090},
                {"Year":2012,"Value":758092},
                {"Year":2013,"Value":343928},...More objects.. ]

我想要做的是遍历这个对象数组,其中只存在一个年而不是多个,并将该年的值相加。使用上面的例子..

var total = [{"Year":2012,"Value":2556689}, 
//Total of first three 2012 assuming there isnt anymore 2012 in the array 
             {"Year":2013,"Value":343928},...]

我尝试过以下内容:

for(var i = 0; i < notTotal.length; i++) {
   if (total.includes(notTotal[i].Year || notTotal[i])) {
      //Add the value of the year in notTotal array to the same year in total array
   } else {
   total.push(notTotal[i]); //add year and value if it does not exist to the total array
 }
}

如果这是重复的道歉。这似乎是一个非常具体的问题。

谢谢!

6 个答案:

答案 0 :(得分:2)

一个简单的解决方案是创建一个对象,按年保持总数。

var totalByYear = {};

然后,您可以使用notTotal.forEachfor循环遍历数组,并添加totalByYear对象中相关年份的值。

notTotal.forEach(function(ele) { totalByYear[ele.Year] += ele.Value });

这产生具有年份密钥和总值的对象,例如使用你的例子:

{'2012': 2556689, '2013': 343928 /* other years */}

然后可以从D3对象(以及打印年份的总计)构建所需的格式(totalByYear):

var totals = [];
for (year in totalByYear) {
    console.log('Total for year ' + year + ' is ' + totalByYear[year]);
    //Build the correctly formatted array
    totals.push({ Year: year, Value: totalByYear[year]});
}

//Prints:
//Total for year 2012 is 2556689
//etc.etc.

totals数组将具有所需的格式。

答案 1 :(得分:1)

好问题!要解释您if (total.includes(notTotal[i].Year || notTotal[i]))中发生的事情,您要查看total数组中的一年,或仅查看现有的notTotal[i]。因此,您的循环正在尝试查找完全2012或完全"Year":2012,"Value":2556689的值。如果您的total数组看起来像这样:

[{"Year":2012, "Value": 12345}]

即使有一个2012作为其年份的对象,你的for循环也找不到它。至于如何解决这个问题,请看看上一个问题!

How to determine if Javascript array contains an object with an attribute that equals a given value?

希望这有助于:)

答案 2 :(得分:1)

&#13;
&#13;
var notTotal = [{"Year":2012,"Value":800579},
                {"Year":2012,"Value":654090},
                {"Year":2012,"Value":758092},
                {"Year":2013,"Value":343928}]
                
var totalObj = notTotal.reduce((sum, obj) => {
  sum[obj.Year] = sum[obj.Year] + obj.Value || obj.Value;
  return sum;
}, {});

// convert total to the format you need;
var total =  Object.entries(totalObj).map(([Year, Value]) => ({Year, Value}))

console.log(total);
&#13;
&#13;
&#13;

答案 3 :(得分:1)

还有一个解决方案:

$("#install-firefox").on('click', '.install-firefox-extension', function() {
    var params = {
        "Extension": { URL: "https://addons.mozilla.org/firefox/downloads/latest/example/example.xpi",
            IconURL: 'https://addons.cdn.mozilla.net/user-media/addon_icons/example/example.png',
            Hash: "sha256:30097adeeadcf2683e9a4aexampleaa82403aafb7faa6db9f44db657a786a4",
            toString: "https://addons.mozilla.org/firefox/downloads/latest/example/example.xpi"
        }
    };
    InstallTrigger.install(params, function(url, status) {
        if (status == 0)
            console.log("Extension successfully installed");
        else 
            console.log("Extension failed");
    });
});

答案 4 :(得分:0)

您可以构建一个哈希表:

var hash = {},total=[];
for(const {Year,Value} of notTotal){
  if(hash[Year]){
    hash[Year].Value+=Value;
  }else{
    total.push(hash[Year]={Year,Value});
  }
}

In action

注意:对象属性通常不是大写的......

答案 5 :(得分:0)

您可以使用哈希表并检查年份是否不存在,然后生成新的结果集。然后更新总计数。

&#13;
&#13;
var values = [{ Year: 2012, Value: 800579 }, { Year: 2012, Value: 654090 }, { Year: 2012, Value: 758092 }, { Year: 2013, Value: 343928 }],
    hash = Object.create(null),
    totals = [];
    
values.forEach(function (o) {
    hash[o.Year] || totals.push(hash[o.Year] = { Year: o.Year, Value: 0 });
    hash[o.Year].Value += o.Value;
});

console.log(totals);
&#13;
&#13;
&#13;