How to display value base on the key from a array list


#1

I have an array list such as

[
      {
        code: 'M',
        name: 'Male'
      },
      {
        code: 'F',
        name: 'Female'
      }
    ]

How can I display a list of people information in view if the gender is M, it will display as Male, else if F, it displays as Female?


#2

You could iterate over your code/name file to build a WeakMap<string, string> where the WeakMap key 'M' is associated to the value 'Male'. Then when displaying people information in your information array, display the value of your map code.


#3

Hi
There are different ways you can achieve this.

<div *ngFor="let people of peoples">
   <small>{{formatGender(people.code)}}</small>     
</div>

//In your controller/component you can have something like this

formatGender(gender){
   if(gender == 'M'){
       return 'Male'
  }else if(gender == 'F'){
      return 'Female'
 }
}

BTW with the way you data is set up you could have something like this

<div *ngFor="let people of peoples">
   <small>{{people.name}}</small>     
</div>

I hope this helps you.


#4

I tried WeakMap, but it has error while set(key, value), so I change to use Map and it works now. I am wondering what is the problem to set(key, value) in WeakMap


#5

Map is fine. You could post the error if you want someone to take a look at it, but WeakMap is new, so maybe your system doesn’t support it for some reason. The main difference is that WeakMap has better garbage colleciton, so it uses less memory. But if you got map working, I wouldn’t worry about it.