我对以下方法有疑问。我出现以下错误Cannot read property 'selectedMAP' of undefined
。
const selectedPlan = {"name": "basic", "amount": 1000}
let dependantsCost = 0;
for (let i = 0; i < this.planCosts[0].selectedMAP.length; i++) {
for (let j = 0; j < this.planCosts[0].selectedMAP[i].options.length; j++) {
if (selection.medicalAid.numberOfAdultDependants > 0) {
const costForAdultDependant = this.planCosts.filter(x => x.selectedMAP[i].options[j].optionName.toLowerCase() == selectedPlan.name.toLowerCase())[0].selectedMAP[i].options[j].adultDependantAmount;
const numberOfAdultDependants = selection.medicalAid.numberOfAdultDependants;
dependantsCost += numberOfAdultDependants * costForAdultDependant;
}
}
}
这是我要过滤的数据集
[
{
"corporateId": "a682fafc-372a-4bbf-9b42-fe8b35cc437f",
"selectedMAP": [
{
"mapId": 32,
"mapName": "one",
"active": true,
"options": [
{
"optionId": 49,
"optionName": "basic",
"memberAmount": 1000,
"adultDependantAmount": 500,
"childDependantAmount": 500,
"active": true
},
{
"optionId": 50,
"optionName": "advanced",
"memberAmount": 2000,
"adultDependantAmount": 1000,
"childDependantAmount": 2000,
"active": true
}
]
},
{
"mapId": 33,
"mapName": "two",
"active": true,
"options": [
{
"optionId": 51,
"optionName": "lite",
"memberAmount": 1000,
"adultDependantAmount": 500,
"childDependantAmount": 500,
"active": true
},
{
"optionId": 52,
"optionName": "heavy",
"memberAmount": 2000,
"adultDependantAmount": 500,
"childDependantAmount": 500,
"active": true
}
]
}
]
}
]
this.planCosts [0]等于this
{
"corporateId": "a682fafc-372a-4bbf-9b42-fe8b35cc437f",
"selectedMAP": [
{
"mapId": 32,
"mapName": "one",
"active": true,
"options": [
{
"optionId": 49,
"optionName": "basic",
"memberAmount": 1000,
"adultDependantAmount": 500,
"childDependantAmount": 500,
"active": true
},
{
"optionId": 50,
"optionName": "advanced",
"memberAmount": 2000,
"adultDependantAmount": 1000,
"childDependantAmount": 2000,
"active": true
}
]
},
{
"mapId": 33,
"mapName": "two",
"active": true,
"options": [
{
"optionId": 51,
"optionName": "lite",
"memberAmount": 1000,
"adultDependantAmount": 500,
"childDependantAmount": 500,
"active": true
},
{
"optionId": 52,
"optionName": "heavy",
"memberAmount": 2000,
"adultDependantAmount": 500,
"childDependantAmount": 500,
"active": true
}
]
}
]
}
你知道为什么这会抛出一个错误吗?
答案 0 :(得分:2)
此部分给出错误
this.planCosts.filter(...)[0].selectedMAP[i]
,
当滤波后的输出的长度变为零时。您可以像这样使用它来避免错误。
const lenOfFiltered = this.planCosts.filter(...).length;
if (lenOfFiltered ) {
this.planCosts.filter(...)[0].selectedMAP[i].options[j].adultDependantAmount;
}
谢谢!