让我说我想从六个对象中找到本金总额,有没有一种方法可以快速完成,而不是按照我的方式进行,这似乎是一种不好的做法,如果数字是多少,将很难使用的对象更多。
var monthlyInfo =[{Date: "Jan 2020", Balance: 747798, Mortgage: 2827, Principal: 2202, Interest: 625}
{Date: "Feb 2020", Balance: 745594, Mortgage: 2827, Principal: 2204, Interest: 623}
{Date: "Mar 2020", Balance: 743388, Mortgage: 2827, Principal: 2206, Interest: 621}
{Date: "Apr 2020", Balance: 741181, Mortgage: 2827, Principal: 2208, Interest: 619}
{Date: "May 2020", Balance: 738972, Mortgage: 2827, Principal: 2209, Interest: 618}
{Date: "Jun 2020", Balance: 736760, Mortgage: 2827, Principal: 2211, Interest: 616}]
monthlyInfo[0].Principal + monthlyInfo[1].Principal + monthlyInfo[2].Principal + monthlyInfo[3].Principal + monthlyInfo[4].Principal + monthlyInfo[5].Principal
答案 0 :(得分:1)
只需像这样使用reduce
:
const principalTotal = monthlyInfo.reduce((a, { Principal }) => a + Principal, 0);
摘要:
var monthlyInfo=[{Date:"Jan 2020",Balance:747798,Mortgage:2827,Principal:2202,Interest:625},{Date:"Feb 2020",Balance:745594,Mortgage:2827,Principal:2204,Interest:623},{Date:"Mar 2020",Balance:743388,Mortgage:2827,Principal:2206,Interest:621},{Date:"Apr 2020",Balance:741181,Mortgage:2827,Principal:2208,Interest:619},{Date:"May 2020",Balance:738972,Mortgage:2827,Principal:2209,Interest:618},{Date:"Jun 2020",Balance:736760,Mortgage:2827,Principal:2211,Interest:616}];
const principalTotal = monthlyInfo.reduce((a, { Principal }) => a + Principal, 0);
console.log(principalTotal);