Pratap Chauhan
Pratap Chauhan

Reputation: 41

Angular4 how to find specific value from an array

I am using Components and service Component :

servers:{Name : string , Id:number }[]=[];

ngOnInit() {
    this.Id =   this.route.snapshot.params['id'];
}

Service :

server_detail=[{Name : 'production',Id    : 1},
               {Name :'Attendance', Id    : 2}];

I am getting Id from the route and want to fetch server name corresponding to that server Id.

Upvotes: 0

Views: 17482

Answers (1)

FAISAL
FAISAL

Reputation: 34673

You can find the specific value using the find() method:

// by Id
let server = this.servers.find(x => x.Id === 1);
// or by Name
let server = this.servers.find(x => x.Name === 'production');

UPDATE according to your comment:

ngOnInit() {
    this.servers = this.alldata.server_detail;
    this.server_Id=  this.route.snapshot.params['id'];

    let server = this.servers.find(x => x.Id === this.server_Id);
    if(server !== undefined) {
        // You can access Id or Name of the found server object.
        concole.log(server.Name);
    }
}

If an object is not found, then the find() method will return undefined.

Upvotes: 12

Related Questions