2

I have a property details which is a nested object. On clicking sign-in i get a form object which has values i want to set the values from the form into the nested object. Why cannot we use the normal .(dot) operator or the [] to chain and access the nested objects and their properties.

export class AppComponent {

    details:{
        city:string,
        dates:{
          date:Date,
          data:{
            name:string,
            comment:string
          }[]
        }[]
      }

     // this function is executed on submit of the form 

     onSignin(form:NgForm){

       console.log(form)
       this.details.city=form.value.city; // cannot set property 'city' of undifined
        console.log(this.details)
    }

}
M.javid
  • 6,387
  • 3
  • 41
  • 56
  • 1
    https://stackoverflow.com/questions/44916365/how-to-create-a-nested-object-json-of-a-form-input-values-based-on-the-input-n – Dženis H. Oct 09 '18 at 05:33
  • https://stackoverflow.com/questions/44916365/how-to-create-a-nested-object-json-of-a-form-input-values-based-on-the-input-n looks different to me. – Matt McCutchen Oct 09 '18 at 06:17

2 Answers2

0

I dont see any problem with your structure or code. It is possible that you may not be assigning the value correctly.

The below code gives me the correct output:

class Example {
  details: {
    city: string,
    dates: {
      date: Date,
      data: {
        name: string,
        comment: string
      }[]
    }[]
  } = {
      city: "Tokyo",
      dates: [
        {
          date: new Date(),
          data: [
            {
              name: "Stackoverflow",
              comment: "Hi"
            }
          ]
        }
      ]
    }


  getDetails() {
    console.log(this.details.city)
    this.details.city = "Hong Kong";
    console.log(this.details.city)
  }
}

new Example().getDetails();

This first prints "Tokyo" and then "Hong Kong". You have just defined details as variable and not assigned any value. Since details is currently undefined, you cannot directly set the value of only one its nested objects. You can set value for city, if details was assigned to any non null value.

codingsplash
  • 4,785
  • 12
  • 51
  • 90
0

As the error message suggests, this.details is undefined. You need to create the object before you can set its properties. For example:

// A cast is required because `this.details` doesn't yet have the required properties.
this.details = {} as any;
this.details.city = form.value.city;
// ...

Or use an object literal instead of setting individual properties:

this.details = {city: form.value.city, dates: [ /*...*/ ]};
Matt McCutchen
  • 28,856
  • 2
  • 68
  • 75