1

How to create enum from a json rest api?

I have this service.ts

getDataFromJson(): Observable<any> {
    return this.httpClient.get<any>(`../../../assets/gender.json`)
      .pipe(map(data => {
        return data;
    }));
  }

but it returns as

[
  {
    "name": "Female",
  },
  {
    "name": "Male",
  }
]

using this code

getGenders: any = {}

getGender() {
    this.options.getDataFromJson().subscribe(data => {
      this.getGenders = data;
    })
  }

instead of this format

{
    Male = 'Male',
    Female = 'Female',
}

I want it to return is as type enum and place it in my gender.ts just like this.

export enum Gender {
    Male = 'Male',
    Female = 'Female',
}
  

Thank you for your help.

vashlor
  • 53
  • 7

1 Answers1

1

I don't think enum is the correct word here. Please consider a constant.

Imagine you have a gender.json file, which includes the following in your project.

[
  {
    "name": "Female"
  },
  {
    "name": "Male"
  }
]

Now you want to create another variable in gender.ts which holds the expected format.

export const genders = {
    Male: 'Male',
    Female: 'Female',
};

To build this genders constant dynamically you need to do 2 things.

1st: Go to your compilerOptions and include those 2 lines:

"resolveJsonModule": true,
"allowSyntheticImports": true

2nd: Go back to gender.ts and import the json file. Then transform the json's content to the expected format.

import genderJson from './gender.json';

export const genders = genderJson
  .map(gender => gender.name).reduce((acc, gender) => {
    acc[gender] = gender;
    return acc;
  }, {});

See working stackblitz: https://stackblitz.com/edit/angular-ivy-uocg2j?file=src%2Fapp%2Fgender.ts

MoxxiManagarm
  • 8,735
  • 3
  • 14
  • 43