2017-01-07 74 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