Aaron
Aaron

Reputation: 109

How to extract id value only from function below? As I am beginner to angular and typescript, I am not able to figure out

I am trying to get location id from the function below. I have a backend service method getLocationList() which returns all the locations with id from database.

 getLocationList() {
      this.service
      .getLogsLocationList()
      .subscribe((data:any) => {
        console.log(data);        
      });
  }

The console output I am getting from function above is as below:

[{id: 1, location :"D:\Aaron\logs\One"}]

I want to get the id value only. How do I do it?

Upvotes: 1

Views: 541

Answers (2)

Wajid
Wajid

Reputation: 593

You can extract Id from this array using loop or if you want to extract for specific index then you can do with index following is complete example of your code

var ids=[]; //i added this array for understanding
     getLocationList() {
          this.service
          .getLogsLocationList()
          .subscribe((data:any) => {
            console.log(data);  
      for(let i=0;i<data.length;i++){
          ids.push(data[i].id)
}
          });
      }

or you can extract by index data[0].id //What ever index you want

Upvotes: 2

JeffryHouser
JeffryHouser

Reputation: 39408

Based on your data structure you have an array of objects.

The square brackets represent an array. The curly brackets represent an object.

As such, if you want to get the ID of the first object in the array, you can do it like this:

console.log(data[0].id);

Upvotes: 1

Related Questions