typescript Angular4 如何从数组中找到特定值
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/45797421/
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
Angular4 how to find specific value from an array
提问by Pratap Chauhan
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.
我从路由中获取 Id 并想获取与该服务器 Id 对应的服务器名称。
回答by Faisal
You can find the specific value using the find()
method:
您可以使用以下find()
方法找到特定值:
// by Id
let server = this.servers.find(x => x.Id === 1);
// or by Name
let server = this.servers.find(x => x.Name === 'production');
UPDATEaccording 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
.
如果未找到对象,则该find()
方法将返回undefined
。