2017-06-12 27 views
-1

我有一個如下所示的數組。如何從數組中獲取字段值並使用Typescript添加值

[{"rowid":1,"amount":5000,"checked":true}, 
{"rowid":2,"amount":1500,"checked":true}, 
{"rowid":3,"amount":500,"checked":true}] 

在那裏我有3行每行中我有一個稱爲字段。我想添加所有金額字段的值,以便我將得到結果。

+0

打字稿只是JavaScript和類型的註釋。它沒有提供任何新功能來處理這樣的問題。順便說一下,這不是一個「Jsonarray」,它是一個「陣列」。關於你自己的問題,循環數組元素和增加每個元素的'amount'屬性有什麼問題嗎? – 2017-06-12 08:51:38

+0

[更好的方式來總結數組中的屬性值(使用Angularjs)](https://stackoverflow.com/questions/23247859/better-way-to-sum-a-property-value-in-an -array-using-angularjs) – 2017-06-12 08:55:40

+0

@ torazaburo。我也不知道JavaScript。我想要使​​用打字稿的解決方案 – ananya

回答

1

要提取amount使用.map和添加項目.reduce

let arraylist = [{"rowid":1,"amount":5000,"checked":true} 
       {"rowid":2,"amount":1500,"checked":true}, 
       {"rowid":3,"amount":500,"checked":true}]; 
const bArray = arraylist.map(({ amount }) => amount); 
const result = bArray.reduce(function(a, b) { return a + b; }, 0); 
console.log(result);  // output = 7000 
+0

非常感謝你@ Cling.This正在爲我工​​作:) – ananya

相關問題