繁体   English   中英

如何根据 Javascript 中的属性过滤对象数组

[英]How to filter an array of objects according to an attribute in Javascript

我有一个用户数组 object 我想过滤这个数组并根据属性角色删除所有管理员用户。

在此处输入图像描述

用户列表由服务返回,我想在 OnInit function 中对其进行过滤:

ngOnInit() {
    this.accountService.getAll()
      .pipe(first())
      .subscribe(accounts => {
        console.log(accounts);
        this.accounts = accounts;
      });

  }

我可以使用哪种 function 来做到这一点?

使用过滤器运算符:

ngOnInit() {
    this.accountService.getAll()
      .pipe(
        first(), 
        filter(e => e.role !== 'Admin'))
      .subscribe(accounts => {
        console.log(accounts);
        this.accounts = accounts;
      });

  }

您可以轻松使用 JS 过滤器 function。 获取所有非管理员用户:

ngOnInit() {
    this.accountService.getAll()
      .pipe(first())
      .subscribe(accounts => {
        console.log(accounts);
        this.accounts = accounts.filter((acct) => acct.role !== "Admin");
      });

  } 

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM