[英]How to get one object property when the object is inside a array?
我正在开发一个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”
我感谢帮助
您可以使用valuePrepareFunction
和filterFunction
来显示您想要的属性并仍然保持过滤功能。
我创建了一个快速的StackBlitz 示例。
唯一的变化是在您的列定义中,如下所示:
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);
}
}
}
}
};
如果您想要 empresa 名称属性的列表,您可以将要转换的用户数组映射到 empresa 的名称。
您可以这样做:
this.mainService.getAllUsers().subscribe(res => {
console.log(res);
const empresaNamesList = res.map(user => user.empresa.nombre);
...
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.