Building an array using class value types in TypeScript

Here is a sample class structure:

export interface ILanguage {
  shortName: string;
  fullName: string;
}
export class Languages {
  static readonly FRENCH: ILanguage = { shortName: 'fr', fullName: 'FRENCH' };
  static readonly DUTCH: ILanguage = { shortName: 'nl', fullName: 'DUTCH' };
}

I want to transform this class into a simple array like this:

const array = [{ shortName: 'fr', fullName: 'FRENCH' }, { shortName: 'nl', fullName: 'DUTCH' }];

I think I need to iterate over the keys of the Languages class using:

Object.keys(Languages).forEach

However, I am unsure about the syntax for pushing the values into the array.

Answer №1

Getting close, consider using the Object.values method.

class Languages {
  static GERMAN = { shortName: 'de', fullName: 'GERMAN' };
  static PORTUGUESE = { shortName: 'pt', fullName: 'PORTUGUESE' };
}
console.log(Object.values(Languages))

Answer №2

Implement a convertToArray method within your Languages class:

static convertToArray() {
  return Object.values(this);
}

Alternatively, you can define it as a getter:

static get asArray {
  return Object.values(this);
}

This approach provides a convenient and reusable way to retrieve your languages as an array, eliminating the need to repeatedly use Object.values(Languages).

Additionally, consider marking your Languages class as abstract if you solely have static members, although this step is not mandatory.

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

Code for most recent adjusted time and date

Looking for a script that can provide me with the last modified time and date of a Google Sheet. I have all the Google Sheet workbook IDs listed in column E of a sheet named 'Planner Directory' and I need to display the last modification details ...

The styling of one unordered list in CSS can be influenced by another unordered

I have been working on developing a menu that is split into three sections: Left Middle Right To achieve this, I utilized the following code snippet: JSFIDDLE However, I noticed that the left menu's layout was being impacted by the middle menu, d ...

retrieve information in json format from a specified web address

I need to figure out why the data from a specific URL is not being displayed properly on my node application. It seems like there might be an error in my code. const extractRefDefaultSchema = async (data) => { const url = "https://mos.esante.gouv.f ...

Modify parent component state when input in child component changes in React

I am working on a parent component called NewPetForm: class NewPetForm extends React.Component { state = { name: '', age: '', animal: '', breed: '' }; render() { ...

What is the best way to retrieve a cookie sent from the server on a subdomain's domain within the client request headers using getServerSideProps

Currently, I have an express application using express-session running on my server hosted at api.example.com, along with a NextJS application hosted at example.com. While everything functions smoothly locally with the server setting a cookie that can be r ...

Leveraging aws-sdk within a TypeScript, jQuery, and webpack application

Greetings! I have a TypeScript/jQuery/Webpack application with all the latest releases, and everything seems to be functioning properly. Now, I am attempting to integrate the aws-sdk into it. I followed the same approach I used for importing other librarie ...

Looking for a way to have a form vanish from every page on your website once it's been

The form on all pages should vanish after the first submission. I am searching for a new code version that leverages a fundamental feature of web browsers $.ajax({ url: 'subscribe.php', type: 'post', data: { email ...

Why is my browser failing to show spaces in list text when using the SELECT tag?

While using IE7, I noticed that the options in my SELECT tag are displayed without the leading spaces in the text - it appears that the text is being trimmed. For instance, in the HTML code block provided below, even though options 1 to 3 have three spaces ...

What is causing fs.readFileSync to not recognize my json document?

So, I've been working on creating a Discord bot that can extract specific data from my JSON file. Here is the structure of my project: Project | +-- data/ | | | +-- compSciCourses.json | +-- src/ | | | +-- search.js | +-- bot.js | +-- t ...

Encountering an error: "Unable to assign the 'id' property to an undefined object while attempting to retrieve it"

I'm running into an issue while attempting to retrieve a specific user from Firebase's Firestore. export class TaskService { tasksCollection: AngularFirestoreCollection<Task>; taskDoc: AngularFirestoreDocument<Task>; tasks: Obs ...

Exploring the power of Vue.js by utilizing nested components within single file components

I have been attempting to implement nested single file components, but it's not working as expected. Below is a snippet of my main.js file : import Vue from 'vue' import BootstrapVue from "bootstrap-vue" import App from './App.vue&apos ...

Dealing with Regular Expressions in Javascript and PHP Challenge

I am struggling to achieve the same outcome with my JavaScript as I do with my PHP code. The issue lies in how JavaScript omits backslashes, unlike PHP. To address this, I have included random forward and backward slashes to cater for different systems. Se ...

Guide on displaying JSON data from a server on a webpage using Google Charts in real-time

Although I am not a JavaScript developer or an expert in AJAX, I consider myself a novice desktop developer. I would greatly appreciate it if you could guide me on how to connect an MCU that returns JSON data to a web page using Google gauge, running on th ...

The bootsrtap modal appears to be invisible and is not displaying on the screen

Having trouble implementing a code to display a bootstrap modal upon clicking a button. The modal is not showing up for some reason. Here is the code snippet: <button type="button" id="asd" data-toggle="modal" data-target= ...

Utilize JavaScript to execute postback calls

Currently, I am working on a project using asp.net MVC5. Within my HTML code, I have the following row: <input id="setCulture" type="hidden" name="culture" value="" /> Accompanied by this JQuery row: $('#setCulture').parents("form"). ...

Ways to eliminate a specific array from another array using JavaScript

0: {id: 1553825061863, name: "Thai Milk Tea", qty: "1", total_amount: 9500, toppings: 500, …} 1: {id: 1553825061863, name: "Thai Milk Tea", qty: "1", total_amount: 9500, toppings: 500, …} 2: {id: 1553825061863, name: "Thai Milk Tea", qty: "1", total_am ...

Show a nested array retrieved from JSON in a React component

I need assistance in displaying data from my JSON file, particularly an innested array using map(). The field I want to display as a list is analyzedInstructions, which looks like this: How to prep (from p How to prep /p) Steps: Remove the cauliflower&a ...

What is the purpose of the JSON.stringify() function converting special characters?

I attempted the following code snippet: console.log(JSON.stringify({ test: "\u30FCabc" })); The result is as follows: '{"test":"ーabc"}' We are aware that primarily, the JSON.stringify() method converts a Jav ...

Value in Hook not updating after memoization of parent component

Let's consider this scenario: import * as React from "react"; const useMyHook = ({ element }: { element: HTMLElement | null }) => { React.useEffect(() => { if (element) { console.log("element in hook", element); ...

Having difficulty invoking a JavaScript function at a global level

Currently, I am working on a nodejs application that involves mongoDB integration. In my code, I have created a function to extract specific data from MongoDB and save it in a variable called "docs". Despite multiple attempts to declare the function global ...