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

Viewed 72

Im developing a Angular 8 app and i have to show in a table the registered users at the moment. 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.

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:

{
_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"

I appreciate the help

2 Answers

You could make use of valuePrepareFunction and filterFunction in order to display the properties you want and still keep filtering capabilities.

I have created a quick StackBlitz example.

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.
Here is how you can do it:

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

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

  ...
}
Related