typescript 从对象数组中获取属性的值

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/41522595/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-21 04:08:43  来源:igfitidea点击:

get value of a property from array of objects

arraysangulartypescript

提问by avokrado

I'm building angular2 app with TypeScript and i came across a problem (note that i'm a noob in angular2 and typescript).

我正在使用 TypeScript 构建 angular2 应用程序,但遇到了一个问题(请注意,我是 angular2 和 typescript 的菜鸟)。

Problem is identical to this: From an array of objects, extract value of a property as arraybut since i'm not using JavaScript, provided solution isn't very helpful (or is it?)

问题与此相同:从对象数组中,将属性的值提取为数组,但由于我没有使用 JavaScript,因此提供的解决方案不是很有帮助(或者是吗?)

I'm getting JSON objects from API and simply save them in array:

我从 API 获取 JSON 对象并将它们保存在数组中:

constructor(private namelistService: NameListService) { }

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

also my simple service:

还有我的简单服务:

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'));
}

resulting in objects like this (i deleted the values):

导致这样的对象(我删除了值):

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

All i want to do is to get the _id values from every object in array and save it in seperate array: arr2 = [id1, id2, id3, id4, ... ]

我想要做的就是从数组中的每个对象中获取 _id 值并将其保存在单独的数组中: arr2 = [id1, id2, id3, id4, ... ]

采纳答案by eko

You can pretty much use any javascript code inside a typescript code since typescript is compiled into javascript itself.

您几乎可以在打字稿代码中使用任何 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'),
  );
}