1

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

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

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

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, ... ]

Community
  • 1
  • 1
avokrado
  • 33
  • 1
  • 1
  • 5
  • 2
    The solution in the question you referred to (using [Array.prototype.map](https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Array/map)) is exactly what you need. Typescript is a superset of javascript, meaning that a js solution is also a ts solution. You can add types, but it's probably not needed as the compiler will in most cases infer the types by itself – Nitzan Tomer Jan 07 '17 at 14:43
  • thank you for quick response. will try that – avokrado Jan 07 '17 at 14:47

1 Answers1

3

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

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'),
  );
}
eko
  • 39,722
  • 10
  • 72
  • 98