2017-08-09 100 views
0

当我尝试使用下面的代码遍历嵌套数组对象时,它不起作用。它是在Typescript或angular4中抛出错误“未定义”的任何问题?在角度4组件中迭代嵌套数组对象时不起作用

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" 
      }] 
} 
} 
+1

在您的示例数据中,事件不是数组,而是键/值映射,其中键事件映射到对象数组 –

+0

'for(let this.process.events.event val)'可能是您意思是这个? – jmw5598

+0

试试这个。这应该工作。 'process:Process [];'你有json对象而不是对象数组。 – micronyks

回答

0

,你可能想要做这样的事情吧。

someMethod() { 

this.process.events.event.map(item => console.log(item.notes)) 

} 

你试着用对象的数组,而不是一个大的一个工作,所以map()似乎更适合这项工作。

+0

这是正确的! – micronyks

+0

不,它不起作用。我不知道为什么它不能获取嵌套的对象元素。 –