How to get a value from an array using ID name in Angular?

I am getting value form API graduated and I want to print original text from below array.

API Response

enter image description here

Current Result as below image

enter image description here

.ts file

 levelEducation = [
    {id: "not-graduated", name: "OTHERS.NotGraduated"},
    {id: "graduated", name: "OTHERS.Graduation"},
    {id: "master", name: "OTHERS.Master"},
    {id: "doctorate", name: "OTHERS.Doctorate"},
  ];

HTML file code

 <div class="form-field">
     <label>{{'JOBAPPLICATION.LevelOfEducation' | translate}}</label>
     <h5>{{userData.livello_studi ? userData.livello_studi : '-'}}</h5>
     <h5 *ngFor="let item of levelEducation">{{(item.name ? item.name : '-' ) | translate}}</h5>
 </div>

So I need to value "OTHERS.Graduation" using ID name graduated in angular.


Solution 1:

The best option is to use a map between livello_studi value and the display value that you want.

I guess OTHERS is an enum, so first you'll need to define the map data.

levelEducation = new Map([
  ["not-graduated", OTHERS.NotGraduated],
  ["graduated", OTHERS.Graduation],
  ["master", OTHERS.Master],
  ["doctorate", OTHERS.Doctorate],
]);

To get data from the map you do it like this

levelEducation.get(userData.livello_studi); // this will return undefined if the item is not found

So you could do this in the template to get the data:

<h5>{{levelEducation.get(userData.livello_studi) || '-'}}</h5>

(or move this code into a function for cleanliness)

Solution 2:

If you want to map the values from graduated to Graduation you can solve this with a map. Assumed you have n values and this is not an editable input.

let map = new Map();
map.set("graduated" ","Graduation");
map.set("not-graduated","Not graduated");

....

and later when you need to display your value you can write a function which displays your displayabletext when you need it.

return map.get("graduated");