2017-01-07 72 views
1

我正在用TypeScript構建angular2應用程序,並且遇到了一個問題(請注意,我是angular2和typescript中的noob)。從對象數組中獲取屬性的值

問題是相同的:From an array of objects, extract value of a property as array但因爲我不是使用JavaScript,提供的解決方案是不是非常有幫助的(是嗎?)

我碰到API JSON對象,並簡單地將它們保存在陣列:

constructor(private namelistService: NameListService) { } 

getAllDevices(){ 
this.namelistService.getDevices() 
.subscribe(
    data => this.devices = data, 
    error => console.log('Server error'), 
); 
} 

也是我的簡單服務:

constructor(private http:Http){} 

getDevices(): Observable<any>{ 
    return this.http.get("http://link-to-api") 
    .map((res: Response) => res.json()) 
    .catch((error: any) => Observable.throw(error.json().error || 'Server error')); 
} 

導致這樣的對象(ⅰ刪除的值):

{ 
"_id": "", 
"info": { 
    "device_id": , 
    "device_name": "", 
    "uid": "", 
    "firmware": "", 
    "hardware": "", 
    "description": "" 
}, 

所有我想要做的是從陣列中的每個對象獲得_id值,並將其保存在單獨的磁盤陣列: ARR2 = [ID1,ID2,ID3,ID4,...]

+2

在你所提到的問題的解決方案(使用[Array.prototype.map](https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Array/map) )正是你需要的。 Typescript是javascript的超集,意味着js解決方案也是ts解決方案。您可以添加類型,但可能不需要,因爲在大多數情況下,編譯器會自行推斷出類型 –

+0

感謝您的快速響應。將嘗試 – avokrado

回答

0

你幾乎可以在打字稿代碼中使用任何javascript代碼,因爲打字稿本身被編譯爲javascript。

constructor(private namelistService: NameListService) { } 

resultArray:any; 

getAllDevices(){ 
    this.namelistService.getDevices() 
    .subscribe(
    (data) => { 
     this.devices = data; 
     this.resultArray = this.devices.map(function(a) {return a["_id"];}); 

    }, 
    error => console.log('Server error'), 
); 
} 
+0

謝謝,作品像一個魅力。我現在覺得有點愚蠢:) – avokrado

+0

@avokrado我們都去過那裏。 – echonax