Reputation: 2116
I have an issue with the following method. I am the following error 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;
}
}
}
This is the data set that I am filtering on
[
{
"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] is equal to 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
}
]
}
]
}
Any idea why this could be throwing me an error?
Upvotes: 0
Views: 46
Reputation: 430
The error gives in this part
this.planCosts.filter(...)[0].selectedMAP[i]
,
when the length of the filtered output becomes zero. You can use it like this to avoid the error.
const lenOfFiltered = this.planCosts.filter(...).length;
if (lenOfFiltered ) {
this.planCosts.filter(...)[0].selectedMAP[i].options[j].adultDependantAmount;
}
Thank you!
Upvotes: 2