-1

I am getting my data from localestorage and saving to my personalInfo object, later i want to send this object to my API, but for some cases my underageChildInfo and beneficiaryInfo wont exist and i get error. how can i remove my array from this object if it doesnt exist in localestorage?

this.data = JSON.parse(localStorage.getItem('policy'));       

get info(): any {
         return this.personalInfo = {
            personalInfoId: 0,
            insurerInfo: {
               firstName:  this.data.calculatorInfo.name,
               lastName : this.data.calculatorInfo.surname,
               phoneNumber: this.data.contactInfo.phone,
               email: this.data.contactInfo.email
            },
            underageChildInfo: this.data.underageChildInfo.map(i =>
              ({
              firstName: i.name,
              lastName: i.surname,
              birthDate: i.birthDate
            })),
            beneficiaryInfo:
            this.data.beneficiaryInfo.map(i =>({
              firstName: i.name,
              lastName: i.surname
            }))
          }
       }

  onSubmit() {
    console.log(this.info);
}

2 Answers2

1

You can do something like the following.

this.data = JSON.parse(localStorage.getItem('policy'));       

get info(): any {
     let keys:Array<any> = Object.keys(this.data);
     let underageChildInfo = keys.indexOf(underageChildInfo);
     let beneficiaryInfo = keys.indexOf(beneficiaryInfo);

     return this.personalInfo = {
            personalInfoId: 0,
            insurerInfo: {
               firstName:  this.data.calculatorInfo.name,
               lastName : this.data.calculatorInfo.surname,
               phoneNumber: this.data.contactInfo.phone,
               email: this.data.contactInfo.email
            },
            underageChildInfo: underageChildInfo!=-1 ?         this.data.underageChildInfo.map(i =>
              ({
              firstName: i.name,
              lastName: i.surname,
              birthDate: i.birthDate
            })) : null,
            beneficiaryInfo: beneficiaryInfo!=-1 ?
            this.data.beneficiaryInfo.map(i =>({
              firstName: i.name,
              lastName: i.surname
            })) : null
          }
       }

  onSubmit() {
    console.log(this.info);
}

Reference link

0

You can use Optional Chaining for this. Change your code to:

this.data.beneficiaryInfo?.map(i =>({
    firstName: i.name,
    lastName: i.surname
}))

By adding the '?' immediately behind 'beneficiaryInfo' JS will first check if beneficiaryInfo exists before executing the map function.

Ofcourse there are a 1.000 other ways to accomplish this. But this would be the simplest. Does it help?

MDN Reference for Optional Chaining