2017-08-09 101 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

不,它不起作用。我不知道爲什麼它不能獲取嵌套的對象元素。 –