简体   繁体   English

当对象在数组中时如何获取一个对象属性?

[英]How to get one object property when the object is inside a array?

Im developing a Angular 8 app and i have to show in a table the registered users at the moment.我正在开发一个Angular 8应用程序,我现在必须在表格中显示注册用户。 I'm using ng2-smart-table to show the users but i have a problem: the response from backend is an array, obviously, but each array has an object and i need to get the property (the name in this case) of each one.我正在使用ng2-smart-table向用户显示,但我有一个问题:来自后端的响应显然是一个数组,但每个数组都有一个对象,我需要获取属性(在本例中为名称)每一个。

Here is the code i have:这是我的代码:

  this.mainService.getAllUsers().subscribe(res => {
  console.log(res);
  this.users = res;
  this.source = new LocalDataSource(this.users);  

The format of res is an array of the following: res的格式是以下数组:

{
_id: "5e5688bd1ef392001775c8c5"
nombre: "NICOLAS"
apellido: "SANABRIA"
email: "nico@ex.co"
nivel: 1
cargo: "Gerente EAP"
password: "$2a$10$jvqdJnIRKC4C9b5oSdmguOZA.UqqV.B7BnN1RhoMelFUk750K5BBW"
empresa: {_id: "5e5688bc1ef392001775c8c4", nombre: "P4", tipo: "EAP", estado: "pendiente", createdAt: "2020-02-26T15:03:24.638Z", …}
estado: "pendiente"
createdAt: "2020-02-26T15:03:25.067Z"
}

The object i need the property is "empresa"我需要属性的对象是“empresa”

I appreciate the help我感谢帮助

You could make use of valuePrepareFunction and filterFunction in order to display the properties you want and still keep filtering capabilities.您可以使用valuePrepareFunctionfilterFunction来显示您想要的属性并仍然保持过滤功能。

I have created a quick StackBlitz example .我创建了一个快速的StackBlitz 示例

The only changes are in your column definition, something like this:唯一的变化是在您的列定义中,如下所示:

  settings = {
    columns: {
      // other columns
      empresa: {
        title: 'Empresa',
        valuePrepareFunction: (empresa) => {
          // I chose to display nombre
          return empresa.nombre;
        },
        filterFunction: (empresa?: any, search?: string) => {
          if (search.length > 0) {
            // Filter by empresa.nombre
            return empresa.nombre.match(search);
          }
        }
      }
    }
  };

If you want the list of the empresa names properties, you can map the user array to be transformed to just the name of empresa.如果您想要 empresa 名称属性的列表,您可以将要转换的用户数组映射到 empresa 的名称。
Here is how you can do it:您可以这样做:

this.mainService.getAllUsers().subscribe(res => {
  console.log(res);

  const empresaNamesList = res.map(user => user.empresa.nombre);

  ...
}

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

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