2017-07-02 44 views
-2

我有一個對象數組,其中需要查看兩個屬性才能得到值。如何查找數組中的對象的多個值在javascript中總結兩個屬性值

let limit = [ 
    { 
     NodeId: "9837f279", 
     NodeName: "Node1", 
     summary: { 
      current: 50, 
      limit: 75 
     } 
    }, { 
     NodeId: "4189f279", 
     NodeName: "Node2", 
     summary: { 
      current: 60, 
      limit: 100 
     } 
    }, { 
     NodeId: "9837f279", 
     NodeName: "Node1", 
     summary: { 
      current: 30, 
      limit: 75 
     } 
    } 
] 

在這裏,我需要添加的所有節點:

summary.current/summary.limit = (50 + 60 + 30)/(75 + 100 + 75) 

我怎樣才能做到這一點使用JavaScript?

+1

你有什麼試過這個嗎? – Li357

+1

這裏通常的做法是,你研究方法來迭代你的數組,嘗試一些代碼,發佈你試過的代碼,並解釋你卡在哪裏。我們並不打算成爲一種編程服務,只是爲您編寫代碼而不嘗試先解決自己的問題。我們的目標是成爲問題解決者,幫助您解決問題。 – jfriend00

回答

1

我建議你親自與Array#reduce

const totalCurrent = limit.reduce((sum, item) => sum + item.summary.current, 0); 
const totalLimit = limit.reduce((sum, item) => sum + item.summary.limit, 0); 

const totalUtilisation = totalCurrent/totalLimit; 
+0

我會閱讀更多關於array.reduce的感謝。這很有幫助 – looneytunes

相關問題