当我尝试使用下面的代码迭代嵌套的数组对象时,它无法正常工作。它在Typescript或angular4中抛出错误“未定义”任何问题?
import { Process, Event } from "./process";
export class ProcessComponent {
process: Process;
someMethod() {
for(let val of this.process.events) {
console.log(val.notes); // throwing error in console showing undefined.
}
}
process.ts
export class Process {
id: number;
includeSaturdays: boolean;
includeSundays: boolean;
events: Event[];
}
export class Event {
id: number;
date: number;
notes: string;
}
示例数据:
{
"id": 1572734,
"includeSaturdays": false,
"includeSundays": false,
"events": {
"event": [
{
"id": 1587532,
"date": 1483209000000,
"notes": "New year"
},
{
"id": 1587533,
"date": 1495909800000,
"notes": "Memorial day"
}]
}
}
答案 0 :(得分:0)
根据您的数据结构,您可能希望做类似的事情。
someMethod() {
this.process.events.event.map(item => console.log(item.notes))
}
您正在尝试使用一组对象,而不是一个大对象,因此map()
似乎更适合此任务。