Angular 2 declaring an array of objects Angular 2 declaring an array of objects arrays arrays

Angular 2 declaring an array of objects


I assume you're using typescript.

To be extra cautious you can define your type as an array of objects that need to match certain interface:

type MyArrayType = Array<{id: number, text: string}>;const arr: MyArrayType = [    {id: 1, text: 'Sentence 1'},    {id: 2, text: 'Sentence 2'},    {id: 3, text: 'Sentence 3'},    {id: 4, text: 'Sentenc4 '},];

Or short syntax without defining a custom type:

const arr: Array<{id: number, text: string}> = [...];


public mySentences:Array<Object> = [    {id: 1, text: 'Sentence 1'},    {id: 2, text: 'Sentence 2'},    {id: 3, text: 'Sentence 3'},    {id: 4, text: 'Sentenc4 '},];

Or rather,

export interface type{    id:number;    text:string;}public mySentences:type[] = [    {id: 1, text: 'Sentence 1'},    {id: 2, text: 'Sentence 2'},    {id: 3, text: 'Sentence 3'},    {id: 4, text: 'Sentenc4 '},];


Another approach that is especially useful if you want to store data coming from an external API or a DB would be this:

  1. Create a class that represent your data model

    export class Data{    private id:number;    private text: string;    constructor(id,text) {        this.id = id;        this.text = text;    }
  2. In your component class you create an empty array of type Data and populate this array whenever you get a response from API or whatever data source you are using

    export class AppComponent {    private search_key: string;    private dataList: Data[] = [];    getWikiData() {       this.httpService.getDataFromAPI()        .subscribe(data => {          this.parseData(data);        });     }    parseData(jsonData: string) {    //considering you get your data in json arrays    for (let i = 0; i < jsonData[1].length; i++) {         const data = new WikiData(jsonData[1][i], jsonData[2][i]);         this.wikiData.push(data);    }  }}