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

时间:2017-08-21 12:41:14

标签: angular typescript

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

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

服务:

CREATE TABLE myTable (
  table_id       INT NOT NULL,
  firstColumn    NVARCHAR(10),
  secondColumn   INT,
  thirdColumn    INT,
  CONSTRAINT DEF_secColumn DEFAULT 0 FOR secondColumn
)

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

1 个答案:

答案 0 :(得分: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