Cuong Vo
Cuong Vo

Reputation: 289

Class/Interface model in angular 2, declaring an array of objects

I need help understanding how to properly create a model class for the data I am using. I know what to do when it is just one array of objects which would be something like:

export class Education {
    complete: boolean;
    course: string;
}

for the json data:

{
  "educationData": [
    {
      "codeschool": [
        {
          "complete": "true",
          "course":"Front end foundations"
        },
        {
          "complete": "false",
          "course": "Front end formations"
        }
      ]
}

But suppose I am taking classes from another school and I have the following json data. I now have two arrays of objects within my educationData :

{
  "educationData": [
    {
      "codeschool": [
        {
          "complete": "true",
          "course":"Front end foundations"
        },
        {
          "complete": "false",
          "course": "Front end formations"
        }
      ],
      "egghead": [
        {
          "complete": "true",
          "course": "Getting started with angular"
        },
        {
          "complete": "true",
          "course": "Learn HTTP in angular"
        }
      ]
    }
  ]
}

Would I just leave the class model the same as

export class Education {
    complete: boolean;
    course: string;
}

Or do I now need to declare both the codeschool and egghead arrays? If this is the correct way to do it, then I know my syntax is completely wrong because I haven't been able to find much info on this type of case:

export class Education {
  codeschool: Array<Objects>;
    {
      complete: boolean;
      course: string;
    },
  egghead: Array<Objects>;
    {
      complete: boolean;
      course: string;
    }
}

Upvotes: 0

Views: 151

Answers (1)

JacobS
JacobS

Reputation: 606

Given the JSON data you provided, I would most likely do something like this:

class Education {
    [key: string]: { complete: boolean, course: string }[]
}

The [key: string] portion is saying that you'll get keys, you don't know what they'll be exactly, but you know they'll be strings (the key holds no special meaning, but I like naming it that for clarity). After seeing this, I would most likely move those objects into their own class, so something like this:

class Education {
    [key: string]: EducationData[]
}

class EducationData {
    complete: boolean;
    course: string;
}

Upvotes: 2

Related Questions