[英]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. 每个学期有5个年级,每个年级有10个科目,每个科目有12-16周,具体取决于学期。
I want to access the data as follow 我想按以下方式访问数据
currentLesson = term.grade.subject.week.data; 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. 为此,我相信我需要创建一个术语数组,其中每个术语均由一个成绩数组组成,然后每个成绩均由一个主题数组组成,然后每个主题数组都包含一个Week / coursesData对象。
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: 当然,如果需要,可以用更复杂的数据类型替换string
,例如:
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;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.