【问题标题】:How to get one object property when the object is inside a array?当对象在数组中时如何获取一个对象属性?
【发布时间】:2020-02-27 21:12:52
【问题描述】:

我正在开发一个 Angular 8 应用程序,我现在必须在表格中显示注册用户。我正在使用ng2-smart-table 向用户展示,但我有一个问题:后端的响应显然是一个数组,但每个数组都有一个对象,我需要获取每个数组的属性(本例中的名称) .

这是我的代码:

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

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"
}

我需要属性的对象是“empresa”

感谢您的帮助

【问题讨论】:

  • res[index].empresa?其中index 来自 for-loop/forEach
  • 您想要一组 emprasa 属性?
  • 我的意思是,ng2-smart-table 会自动设置各个列中的数据,但是当我分配“empresa”数据时,我不想分配对象,而是分配名称, name 是一个属性。

标签: javascript angular frontend


【解决方案1】:

您可以使用valuePrepareFunctionfilterFunction 来显示您想要的属性并保持过滤功能。

我已经创建了一个快速StackBlitz example

唯一的变化是在您的列定义中,如下所示:

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

【讨论】:

  • thanksssss,这正是我需要的,感谢您的帮助!
【解决方案2】:

如果您想要 empresa 名称属性列表,您可以将要转换的用户数组映射为 empresa 的名称。
以下是你可以做到的:

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

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

  ...
}

【讨论】:

  • 我试过了,但我不需要将 empresa 显示为对象,而是它的属性,你明白吗?
  • 是的,我明白你想要什么,只要看看这段代码,我已经映射到你想要显示的确切属性 res.map(user => user.empresa.nombre);
  • 它给我带来了 empresa 名称,但我不仅需要名称,还需要其余的 res 数据。问题在于 LocalSourceData,它会自动将数据分配给我的表,所以在 empresa 列中我得到 [Object object],但我需要名称,你明白吗?
  • 标记的向上评论对我有用,感谢您的帮助!
猜你喜欢
  • 2022-11-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-11-14
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多