2016-10-04 25 views
1

例如我有5個對象:總和在對象值如果多個密鑰是相同的JS

{ row: aa, col: 1, value: 1 } 
{ row: bb, col: 2, value: 1 } 
{ row: bb, col: 3, value: 1 } 
{ row: aa, col: 1, value: 1 } 
{ row: aa, col: 2, value: 1 } 

我想如果山口是相同的求和值,因此輸出應該是:

{ row: aa, col: 1, value: 2 } 
{ row: bb, col: 2, value: 1 } 
{ row: bb, col: 3, value: 1 } 
{ row: aa, col: 2, value: 1 } 

感謝您的幫助!

嘗試這樣做: Sum javascript object propertyA values with same object propertyB in array of objects

+0

@DanielShillcock更新我的問題 –

+3

你能告訴怎麼樣你已經嘗試適用於您的問題,否則我們不會知道你有問題什麼時候。 –

+0

請創建一個[MCVE](http://stackoverflow.com/help/mcve)。另見http://www.sscce.org/。你必須展示你自己爲解決這個問題而付出的努力。這裏沒有人有義務從頭給你一個解決方案,但我們會幫助你改進你的嘗試。 – Oka

回答

4

您可以reduce()和一個對象存儲密鑰做到這一點。

var data = [ 
 
    { row: 'aa', col: 1, value: 1 }, 
 
    { row: 'bb', col: 2, value: 1 }, 
 
    { row: 'bb', col: 3, value: 1 }, 
 
    { row: 'aa', col: 1, value: 1 }, 
 
    { row: 'aa', col: 2, value: 1 } 
 
] 
 

 
var o = {} 
 
var result = data.reduce(function(r, e) { 
 
    var key = e.row + '|' + e.col; 
 
    if (!o[key]) { 
 
    o[key] = e; 
 
    r.push(o[key]); 
 
    } else { 
 
    o[key].value += e.value; 
 
    } 
 
    return r; 
 
}, []); 
 

 
console.log(result)

+0

是的!這正是我想要的! :) –

1

我會做的是把你的對象數組,然後遍歷這一點,在每次迭代檢查是否有新對象的關鍵字相匹配的是一箇舊的和加載的對象如果沒有匹配,則將其轉換爲單獨的數組。如果它匹配,則將其值添加到舊的值中。我測試了下面的代碼,它似乎工作如何你想要的。

var array = [{ row: 'aa', col: 1, value: 1 }, 
     { row: 'bb', col: 2, value: 1 }, 
     { row: 'bb', col: 3, value: 1 }, 
     { row: 'aa', col: 1, value: 1 }, 
     { row: 'aa', col: 2, value: 1 }]; 

var newArray = []; 

for(var x in array) { 
    for(var y in newArray) { 
     var found = false; 
     if(array[x].row == newArray[y].row && array[x].col == newArray[y].col) { 
      newArray[y].value += array[x].value; 
      found = true; 
      break; 
     } 
    } 
    if(!found) { 
      newArray.push(array[x]); 
    } 
} 

console.log(newArray); 
2

只是爲了完整起見,使用變量鍵的版本,用於對零件進行分組的對象和Array#forEach

var data = [{ row: 'aa', col: 1, value: 1 }, { row: 'bb', col: 2, value: 1 }, { row: 'bb', col: 3, value: 1 }, { row: 'aa', col: 1, value: 1 }, { row: 'aa', col: 2, value: 1 }], 
 
    grouped = []; 
 

 
data.forEach(function (a) { 
 
    var key = ['row', 'col'].map(function (k) { return a[k]; }).join('|'); 
 
    if (!this[key]) { 
 
     this[key] = { row: a.row, col: a.col, value: 0 }; 
 
     grouped.push(this[key]); 
 
    } 
 
    this[key].value += a.value; 
 
}, Object.create(null)); 
 

 
console.log(grouped);
.as-console-wrapper { max-height: 100% !important; top: 0; }

相關問題