Generating Enums from JSON REST API in Angular 8

Is there a way to create an enum from a JSON REST API?

Here is the code I currently have in my service.ts file:

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

However, the data is returned in this format:

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

Using this code:

getGenders: any = {}

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

Instead of the current format, I would like the data to be returned as an enum type and placed in my gender.ts file like this:

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

Any suggestions on how to achieve this are greatly appreciated.

Answer №1

It might be more appropriate to use a constant instead of an enum in this scenario.

Consider a scenario where you have a gender.json file with the following data:

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

You can create a variable in a gender.ts file to store this data in the desired format.

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

In order to dynamically build the genders constant, you will need to take two steps.

First, update your compiler options with the following:

"resolveJsonModule": true,
"allowSyntheticImports": true

Secondly, import the gender.json file in gender.ts and transform the data to the desired format.

import genderJson from './gender.json';

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

For a demonstration, you can view a working example on StackBlitz: https://stackblitz.com/edit/angular-ivy-uocg2j?file=src%2Fapp%2Fgender.ts

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Achieve an overlapping effect between absolutely positioned sibling divs without the need to specify a background color

Exploring the development of a swipe-to-action list component. <div class="list-container"> <div class="row"> <div class="content"> Sample Content 1 </div> <div class="action"> ...

JavaScript Error: Unable to execute getJsonData due to function not found

I am encountering an issue with a function that retrieves JSON data from a URL Here is the code snippet: var retrieveJsonData = function(uri,callback){ $.ajax({ type: "GET", dataType: "jsonp", url: uri, jsonpCallback: 'r ...

Looking for advice on successfully implementing createMultiMaterialObject in THREE.js version r62?

I am having trouble getting createMultiMaterialObject to work as expected. My goal is to have a wireframe material displayed on top of a solid material. However, the multimaterial function only seems to display the first material in the array. Here is the ...

Leveraging class names to dynamically apply CSS styles to components based on their props value

In the process of developing a collection of reusable components, I have utilized material-ui and styled them with CSS. One specific requirement is to dynamically set the width of a component through a prop passed into a custom button. My goal is to lever ...

How can we initiate the AJAX request right away while also making sure the page is fully loaded before adding

One trick I've discovered is that by submitting an AJAX request in the <head> section of my webpage, I can avoid a minor flicker on page load when loading content via AJAX. Of course, this method still needs some refining to handle longer AJAX r ...

How to retrieve a string from a regular expression in Javascript without [Object object] output

Within my code, there exists a parent form component and a child component used for auto-completing text input. The Parent component passes an array of objects named autoCompTxt, consisting of name and id fields, to the Child component. //Parent: const [ob ...

Tips for managing a date picker with JavaScript using the Selenium WebDriver

I have been attempting to scrape a travel website using Selenium Webdriver and Python. While I have successfully set the destination (destino) and place of origin (origem), I am encountering difficulties when trying to select a date. I understand that Ja ...

Transferring User ID from Google Tag Manager to GA4 Problem

I'm currently working on a new project and adding some dummy data to the dataLayer of Google Tag Manager from the \_app.tsx file. <Script id="gtg" strategy="beforeInteractive"> { window.dataLayer = window.dataLayer || &b ...

I am looking to replicate a DOM element using Angular 4

I am interested in creating a clone of a DOM element. For example, if I have the following structure: <div> <p></p> <p></p> <p></p> <p></p> <button (click)="copy()"></button> & ...

Issue with TypeScript in Vue3: Unable to access computed property from another computed property

In my Vue3 project with TypeScript, I am encountering an issue where I am unable to access the properties of the returned JavaScript object from one computed property in another computed property using dot notation or named indexing. For instance, when tr ...

Move and place multimedia items using IE's drag and drop feature

Is there a way to enable the drag and drop feature across different browsers or windows using HTML5's native DnD API? I have noticed that when I set the data type to 'text' in Internet Explorer, it functions properly. However, if I attempt t ...

I was surprised by how Await behaved in if-else statements, it was not what

let metadata = []; allNFTs.map(async (e) => { if (e.metadata) { metadata.push(JSON.parse(e.metadata).attributes); } else { let config = { method: "get", url: `http://localhost:3000/api/fetch ...

Empty results in NgRx Parameterized Selector

Having trouble implementing a parameterized query in NgRx and receiving empty results. Check out the StackBlitz version of the code here: https://stackblitz.com/edit/ngrx-parameterized-query Update to Reducer Code export const userAdapter = createEntity ...

What is the reason behind JavaScript's `fn.length` returning the count of named parameters that `fn` function has?

Why does calling fn.length in JavaScript return the number of named arguments fn has? > function fn () { } > x.length 0 > function fn (a) { } > x.length 1 > function fn (a,b,c) { } > x.length 3 This behavior is quite peculiar. I wonde ...

Enhance the original array of a recursive treeview in VueJS

After going through this tutorial, I decided to create my own tree view using recursive components in Vue.js. The structure of the input array is as follows: let tree = { label: 'root', nodes: [ { label: 'item1', nod ...

Ways to troubleshoot and fix the problem of encountering an "Internal Server Error" when sending emails with nodeMailer in node.js

When attempting to send a confirmation email using nodemailer, I encountered an internet server error in production when allowing insecure apps for Gmail accounts, although it works fine locally. Any suggestions on how to resolve this issue? router.post(& ...

Search for all documents in MongoDB and update all of them except for one

After performing a database lookup, I am receiving an array of objects as a result. [ { name: "test", services: { credentials: "123456" } }, { name: "test1", services: { credentials: "1 ...

When using the updateMany function, only update the field if it already exists, without creating a new key

My goal within the $set operation is to update a field only if it already exists. While $cond seems to be on the right track, it has the drawback of always creating the field, which is not what I want. Filtering to retrieve only existing fields seems like ...

`Is there a way to effectively test an @Input component in Angular?`

Despite multiple successful attempts in the past, I am facing some difficulty getting this to function properly. Within my component, I have an input @Input data: Data, which is used in my template to conditionally display certain content. Oddly enough, du ...

Enhance Your Webpage with jQuery Drag and Drop Feature Across Multiple Lists

I've been successfully using "jQuery UI Sortable connectwith" for drag & drop functionality, as shown in the example here: . However, I now need to implement drag & drop with multiple UI elements and it's not functioning correctly. Example: < ...