【发布时间】:2018-01-12 18:31:41
【问题描述】:
我一直在使用 map 和 reduce 来处理一些迄今为止运行良好的对象和数组,但是我在处理一个数组时遇到了问题。
此处的数据示例:
var arr =
[
[
{
"id": 6501511,
"invoiceId": {
"id": 1043773
},
"chargeBandType": "TIME",
"jobTaskId": {
"id": 19399852
},
"invoicedNet": {
"amountString": 0,
"currencyType": "USD"
},
"invoicedTaxOneOtherCurrency": null,
"invoicedTaxOne": {
"amountString": 0,
"currencyType": "USD"
},
"taxOneRate": 0.1
},
{
"id": 6501517,
"invoiceId": {
"id": 1043773
},
"chargeBandType": "TIME",
"jobTaskId": null,
"jobExpenseId": null,
"jobThirdPartyCostId": {
"id": 20602
},
"invoicedNet": {
"amountString": 0,
"currencyType": "USD"
},
"invoicedTaxOneOtherCurrency": null,
"invoicedTaxOne": {
"amountString": 0,
"currencyType": "USD"
},
"taxOneRate": 0.1
},
{
"id": 6501508,
"invoiceId": {
"id": 13773
},
"chargeBandType": "TIME",
"jobTaskId": {
"id": 19398574
},
"invoicedNet": {
"amountString": 30,
"currencyType": "USD"
},
"invoicedTaxOneOtherCurrency": null,
"invoicedTaxOne": {
"amountString": 3,
"currencyType": "USD"
},
"taxOneRate": 0.1
},
{
"id": 65014,
"invoiceId": {
"id": 104
},
"chargeBandType": "TIME",
"jobTaskId": null,
"jobExpenseId": null,
"jobThirdPartyCostId": {
"id": 206
},
"invoicedNet": {
"amountString": 0,
"currencyType": "USD"
},
"invoicedTaxOneOtherCurrency": null,
"invoicedTaxOne": {
"amountString": 0,
"currencyType": "USD"
},
"taxOneRate": 0.1
}],
[
{
"id": 6483,
"invoiceId": {
"id": 1042400
},
"chargeBandType": "TIME",
"jobTaskId": {
"id": 198574
},
"invoicedNet": {
"amountString": 100,
"currencyType": "USD"
},
"invoicedTaxOneOtherCurrency": null,
"invoicedTaxOne": {
"amountString": 10,
"currencyType": "USD"
},
"taxOneRate": 0.1
}
]
];
我正在尝试减少 invoicedNet.amountString 的值,在上述情况下,这将带来 130 的总和。
我尝试了很多方法来解决这个问题,包括类似于以下的功能:
var sum = arr.reduce(function(a, b) {
return a += b.invoicedNet.amountString;
}, 0);
但是,无论我如何尝试,我都会不断收到错误消息:
TypeError: Cannot read property 'amountString' of undefined
(不过,它似乎将 b.invoicedNet 作为一个对象)。
任何人都可以建议一种方法吗?
谢谢!
【问题讨论】:
标签: javascript arrays json object reduce