1 回答

TA貢獻(xiàn)1891條經(jīng)驗(yàn) 獲得超3個(gè)贊
因此,假設(shè)您有變量名為 salesReport 的數(shù)據(jù),如下所示:
{
"sales": {
"totals": {
"2015-01-18": {
"sales": "-17.00",
},
"2015-01-21": {
"sales": "597.10",
},
"2015-02-18": {
"sales": "32.00",
},
"2015-03-12": {
"sales": "22.00",
},
},
}
}
然后,您希望訪問每個(gè)日期的 sales.totals 數(shù)據(jù),而無需知道關(guān)鍵詳細(xì)信息。此外,如果您需要存儲(chǔ)密鑰(在本例中為日期)及其各自的值,那么您可以首先使用Object.entries將它們轉(zhuǎn)換為條目,如以下代碼所示:
const salesReportTotalsEntries = Object.entries(salesReport.sales.totals);
然后您可以使用以下命令訪問每個(gè)日期的銷售數(shù)據(jù)
salesReportTotalsEntries[0][1].sales
salesReportTotalsEntries[1][1].sales
最后一步是,您可以使用Array.reduce根據(jù)每個(gè)月的數(shù)據(jù)對(duì)每個(gè)總銷售數(shù)據(jù)進(jìn)行求和。這是完整的代碼:
const salesReport = {
"sales": {
"totals": {
"2015-01-18": {
"sales": "-17.00",
},
"2015-01-21": {
"sales": "597.10",
},
"2015-02-18": {
"sales": "32.00",
},
"2015-03-12": {
"sales": "22.00",
},
},
}
};
const salesReportTotalsEntries = Object.entries(salesReport.sales.totals);
const salesReportTotalsByMonths = salesReportTotalsEntries.reduce((a, v) => {
const currentMonth = v[0].split('-')[1];
if (!a[currentMonth]) {
a[currentMonth] = Number(v[1].sales);
return a;
}
a[currentMonth] += Number(v[1].sales);
return a;
}, {});
console.log(`Total Sales Report in January is ${salesReportTotalsByMonths['01']}`);
console.log(`Total Sales Report in February is ${salesReportTotalsByMonths['02']}`);
添加回答
舉報(bào)