我有一個包含以下對象的數組。遍歷一個對象數組並根據條件添加到其他數組
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
}
}
道歉,如果這是一個重複。這似乎是一個非常具體的問題。
謝謝!
你所需要的最終結果('total')是一個數組?使用將字符映射到值的字典可以非常容易地實現(因爲鍵必須是唯一的)。 – AstroCB
請參閱[這個答案](https://stackoverflow.com/questions/23521894/how-to-aggregate-objects-properties)。 –
它需要是一個數組,然後將其插入到D3條形圖佈局中。 – Stu