简体   繁体   中英

Typescript Array of Array of Array of Objects

I have a curriculum that doesn't need to be changed dynamically so I want to hard code it in service in my angular project.

The data is as follows:

Term 1 Term 2 Term 3

Each term has 5 grades Each grade has 10 subjects Each subject has 12-16 weeks depending on the term.

I want to access the data as follow

currentLesson = term.grade.subject.week.data;

To do this, I believe I need to make a Term Array which each term consists of a grade array which then each grade consists of a subject Array which then each subject Array consists of An object of week / curriculumData.

I can make the last simple Array of objects but my mind shuts down trying to do the array of Array of Array of objects.

Or is there a better way to achieve this?

If all of your 'data' is a simple string, you could simply create a multidimensional array like this:

const lessons: string[][][][] = buildLessons();
const currentLesson = lessons[t][g][s][w];

Of course, you could replace string with a more complicated datatype if you wanted to, eg:

interface Lesson {
  data: string;
  otherProperty: number;
}
const lessons: Lesson[][][][] = buildLessons();
const currentLesson = lessons[t][g][s][w];
// do something with currentLesson.data, etc

Alternatively, if you want to use an object structure, you could also write that out in a more readable way by splitting into separate interfaces, like so:

interface Curriculum {
  term: number;
  grades: Grade[];
} 

interface Grade {
  id: number;
  subjects: Subject[];
}

interface Subject {
  id: number;
  weeks: Week[];
}

interface Week {
  id: number;
  data: string;
}

let example: Curriculum;
const currentLesson = example.grades[g].subjects[s].weeks[w].data;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM