Problem Initializing array (TypeScript)

1

I am trying to copy properties of an object ( response.projects[i].name ) to an array. I have this:

response=>{
                if (response.projects){

                    this.projects=response.projects;

                    console.log(this.projects[0]);
                    for (var i=0;i<response.projects.length;i++){

                        if (typeof this.projects[i].name !="undefined"){
                            this.names[i]=this.projects[i].name;
                        }
                    }
                }
            }

However, I get the error

  

can not set property 0 of undefined

Referring surely to this.names[0] . I do not know how I would have to write the code to make it work.

    
asked by Ayrton 29.12.2018 в 19:51
source

1 answer

0

Make sure that this.names is defined, putting something like

before the loop
this.names = this.names || [];
    
answered by 30.12.2018 / 09:34
source