Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Initializing array of objects - Angular

I have an array of objects and when I try to access to it, I get an error saying:

TypeError: Cannot set property 'ID' of undefined

My code is the following:

export class Carimplements OnInit {
  pieces: Piece[] = [];

  test(pos){
    this.pieces[pos].ID = "test";
  }
}

being Piece an object

export class Piece{
    ID: string;
    doors: string;
}

I call to test(pos) from the HTML with a valid position.

I guess that I am trying to access to the position X of an array that has not been initialized. How could I do it? Is it possible to create a constructor?

like image 259
bellotas Avatar asked Mar 19 '18 11:03

bellotas


People also ask

How do you initialize an array of objects in TypeScript?

To declare an array of objects in TypeScript, set the type of the variable to {}[] , e.g. const arr: { name: string; age: number }[] = [] . Once the type is set, the array can only contain objects that conform to the specified type, otherwise the type checker throws an error. Copied!

What is the type of array of objects in TypeScript?

An array of Objects is used to store a fixed-size sequential collection of elements of the same type. TypeScript Arrays are themselves a data type just like a string, Boolean, and number, we know that there are a lot of ways to declare the arrays in TypeScript.

How do you initialize an array t?

We declare an array in Java as we do other variables, by providing a type and name: int[] myArray; To initialize or instantiate an array as we declare it, meaning we assign values as when we create the array, we can use the following shorthand syntax: int[] myArray = {13, 14, 15};

What is array in angular?

An array is a special type of data type which can store multiple values of different data types sequentially using a special syntax. TypeScript supports arrays, similar to JavaScript.


2 Answers

  • Correct syntax for defining array types in TypeScript is this:

    pieces: Piece[] = [];
    
  • The error is a runtime error. When you run your app you have an empty array pieces (but the variable still initialized with []) but you call test(whatever) which tries to access an array element whatever that doesn't exist.

    You can do for example this:

    pieces: Piece[] = [{
      ID: '1',
      doors: 'foo'
    }];
    

    and then test this method with test(0).

like image 81
martin Avatar answered Oct 02 '22 17:10

martin


let pieces: Piece[]  = [];

//initialize object before assigning value
test(pos){
    this.pieces[pos] = new Piece();
    this.pieces[pos].ID = "test";
  }
like image 34
Shashidhar Mayannavar Avatar answered Oct 02 '22 16:10

Shashidhar Mayannavar