Print field of an array in Angular

2

I have a function in Angular that brings an array with user data, among which one field is user.type_identity_id, and I have another function where I bring the types of identities, how can I compare and according to the user.type_identity_id print the field type_identity.name in HTML

user = [{id: 25, tipo_identidad_id: 1, identidad: 2121212}]

tipo_identidad= [
  {
    "id": 1,
    "name": "DNI"
  },
  {
    "id": 2,
    "name": "Pasaporte"
  },
  {
    "id": 3,
    "name": "RUC"
  }]

<h3>Tipo de Identidad:</h3><b>{{tipo_identidad.name}}</b>

    
asked by mserradas 10.04.2018 в 16:55
source

2 answers

2

You can do with the "find ()" function in your identity_id array. I leave an example in Angular.

//our root app component
import {Component, NgModule} from '@angular/core'
import {BrowserModule} from '@angular/platform-browser'

@Component({
  selector: 'my-app',
  template: '
   <div>
      <h2>Hello {{name}}</h2>
    </div>
  ',
})

export class App {
  name:string;
  user[] = [{id: 25, tipo_identidad_id: 1, identidad: 2121212}];
  tipo_identidad[] = [
 {
    "id": 1,
    "name": "DNI"
  },
  {
    "id": 2,
    "name": "Pasaporte"
  },
  {
    "id": 3,
    "name": "RUC"
  }];

  constructor() {
    var item = this.tipo_identidad.find(x=>x.id == 
    this.user[0].tipo_identidad_id);
    this.name = item.name;
  }
}

@NgModule({
  imports: [ BrowserModule ],
  declarations: [ App ],
  bootstrap: [ App ]
})
export class AppModule {}
    
answered by 10.04.2018 / 17:10
source
1

To access the data of a array you can access by the position of the array and the attribute that interests you. For example:

var user = [{id: 25, tipo_identidad_id: 1, identidad: 2121212}];

var tipo_identidad= [ { "id": 1, "name": "DNI" }, { "id": 2, "name": "Pasaporte" }, { "id": 3, "name": "RUC" }];

var tipoIdentidad = user[0].tipo_identidad_id;

var nombreIdentidad = getNameIdentidad(tipoIdentidad);

console.log(nombreIdentidad);

function getNameIdentidad(tipoIdentidad){
    for(var i = 0; i < tipo_identidad.length; i++){
        if(tipo_identidad[i].id == tipoIdentidad){
            return tipo_identidad[i].name;
        }
    }
    return null;
};

In the variable Identity type you have the value that interests you. From here you can insert it in the HTML.

var user = [{id: 25, tipo_identidad_id: 1, identidad: 2121212}];

var tipo_identidad= [ { "id": 1, "name": "DNI" }, { "id": 2, "name": "Pasaporte" }, { "id": 3, "name": "RUC" }];

var tipoIdentidad = user[0].tipo_identidad_id;

var nombreIdentidad = getNameIdentidad(tipoIdentidad);

console.log(nombreIdentidad);

function getNameIdentidad(tipoIdentidad){
    for(var i = 0; i < tipo_identidad.length; i++){
        if(tipo_identidad[i].id == tipoIdentidad){
            return tipo_identidad[i].name;
        }
    }
    return null;
};
    
answered by 10.04.2018 в 17:07