Angular4如何从数组中查找特定值

问题描述 投票:0回答:1

我正在使用组件和服务组件:

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

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

服务:

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

我从路由获取Id并希望获取与该服务器Id对应的服务器名称。

angular typescript
1个回答
10
投票

您可以使用find()方法找到特定值:

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

根据您的评论更新:

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

如果找不到对象,那么find()方法将返回undefined

© www.soinside.com 2019 - 2024. All rights reserved.