簡體   English   中英

遍歷對象數組並將值加在一起

[英]Iterate over an array of objects and add values together

這似乎很基本,但我無法弄清楚。 我有以下數組

var myArray = [{a:3, b:4, c:5}, {a:-1, b:3, c:5}, {a:0, b:-3, c:1}];

我想遍歷此數組並將所有的a,b,c加在一起。 我想循環執行此操作,因為我不知道數組中有多少個對象。

如:

var A = myArray[0].a + myArray[1].a + myArray[2].a;

您可以使用reduce()並在單獨的變量中為每個鍵返回結果。

 var myArray = [{a:3, b:4, c:5}, {a:-1, b:3, c:5}, {a:0, b:-3, c:1}]; var A = myArray.reduce(function(r, e) { return r + ea; }, 0) console.log(A) 

或者,您可以使用reduce()Object.keys()在一個變量中返回每個對象的屬性的總和。

 var myArray = [{a:3, b:4, c:5}, {a:-1, b:3, c:5}, {a:0, b:-3, c:1}]; var result = myArray.reduce(function(r, e) { Object.keys(e).forEach(function(k) { r[k] = (r[k] || 0) + e[k]; }); return r; }) console.log(result); 

也許這會有所幫助。

var sumA = 0, sumB =0, sumC =0;
myArray.forEach(function(v){
  if (v.hasOwnProperty("a") {sumA += v["a"];}
  if (v.hasOwnProperty("b") {sumB += v["b"];}
  if (v.hasOwnProperty("c") {sumC += v["c"];}
});

forEach()可以工作:

var myArray = [{a:3, b:4, c:5}, {a:-1, b:3, c:5}, {a:0, b:-3, c:1}];
var A = 0;
myArray.forEach(x => {A += x.a});
console.log(A); // 2

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM