Converting an enum into a key-value array in TypeScript: A simple guide

var enums = {
  '1': 'HELLO',
  '2' : 'BYE',
  '3' : 'TATA'
  };

I am seeking a solution to convert the above object into an array that resembles the following structure,

[
  {
    number:'1',
    word:'HELLO'
  },
  {
    number:'2',
    word:'BYE'
  },
  {
    number:'3',
    word:'TATA'
  }
]

Most available solutions focus on creating an array of either keys or values, lacking the specific format I am looking for.

Answer №1

A great way to simplify the process is by using shorthand properties when mapping the entries.

var enums = { 1: 'HELLO', 2: 'BYE', 3: 'TATA' },
    objects = Object.entries(enums).map(([number, word]) => ({ number, word }));

console.log(objects);
.as-console-wrapper { max-height: 100% !important; top: 0; }

Answer №2

To transform your data into the desired format, you have the option to utilize Object.entries along with map

var enums = {
  '1': 'HELLO',
  '2' : 'BYE',
  '3' : 'TATA'
  };
  
let op = Object.entries(enums).map(([key, value]) => ({ number:key, word:value }))

console.log(op)

Answer №3

One workaround is utilizing a for ... in loop to cycle through the enums keys and assemble the desired array of objects.

var enums = {
  '1': 'HELLO',
  '2' : 'BYE',
  '3' : 'TATA'
};

let res = [];

for (key in enums)
{
    res.push({number: key, word: enums[key]});    
}

console.log(res);
.as-console {background-color:black !important; color:lime;}
.as-console-wrapper {max-height:100% !important; top:0;}

Answer №4

One way to achieve this is by utilizing Object.keys along with map

var obj = {
  '1': 'HELLO',
  '2' : 'BYE',
  '3' : 'TATA'
};


const result = Object.keys(obj).map(el => {
  return {
    number: el,
    word: obj[el]
  }
})

console.log(result)

Answer №5

If you want to create an object of Map type and retrieve values by using the get method, you can do so with the following code snippet: outData.get("1")

var obj = {
    '1': 'HELLO',
    '2': 'BYE',
    '3': 'TATA'
};
var outData = new Map();
Object.keys(obj).forEach(function (e) {
    outData.set(e, obj[e])
});

To access the data, use outData.get("key")

The output will look like this:

Map(3) {"1" => "HELLO", "2" => "BYE", "3" => "TATA"}

Answer №6

To utilize Object.entries() in conjunction with foreach and store it in an array, follow this example:

var categories = {
    '1': 'APPLE',
    '2' : 'BANANA',
    '3' : 'CHERRY'
    };

var categoryArray = []
Object.entries(categories).forEach(([id, name]) => categoryArray.push({code : id, fruit : name}));

console.log(categoryArray);

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

Tips for Choosing the Right Objects in Vue.js

I have the following code that combines all objects in a person and stores them in an array called Cash:[] this.cash = person.userinvoice.concat(person.usercashfloat) Inside person.usercashfloat, there is an element called validate which sometimes equals ...

Utilizing Redux state data in a hyperlink: A step-by-step guide

I am a beginner in Redux and ReactJS. I'm working on using a state data called type within the link retrieved via Axios on line 17. The value of type is set from another .jsx file using dispatch(). In this Home.jsx file, dispatch is called on line 24 ...

Encountered a hiccup during the deployment of an Angular application on Heroku

I've been working on deploying an Angular app called "test-app" to Heroku via GitHub and everything seems to be going smoothly, except for setting up the express routing function. I've tried different paths, but Heroku keeps throwing this error: ...

Join the Observable and formControl in Angular 4 by subscribing

My goal is to display the data retrieved from FireStore in the screen fields upon loading. However, the buildForm() function is being called before subscribing to the data, resulting in the failure to populate the screen fields with the FireStore data. pe ...

Managing the jQuery.noConflict function

Upon review, I noticed that the scripts I inherited start like this: var $j = jQuery.noConflict(); The purpose behind this code is not clear to me. While I understand the intent is to avoid conflicts, I am uncertain about the specific conflict it aims to ...

Guide to direct express.js requests straight to 404 page

I need guidance on how to direct a request to a specific route in express.js directly to a 404 error page if the user is not authenticated. Currently, my middleware includes the following code: exports.isAuthenticated = function (req, res, next) { if ( ...

Obtain specific fields from a multidimensional array object using lodash

My dilemma involves working with an object that has the following structure: var data = [ { "inputDate":"2017-11-25T00:00:00.000Z", "billingCycle":6, "total":1 },{ "inputDate":"2017-11-28T00:00:00.000Z", "bi ...

Interact with HTML style attribute using JavaScript

Is there a way to retrieve a specific CSS property from the style attribute of an HTML element, without considering the stylesheet or computed properties? For example: <div style="float:right"></div> function fetchStyleValue(element, propert ...

Is there a way to access a component based on the parameter in the Vue router?

I am working on a Vue component called Portfolio.vue, which contains a child component called Category.vue. I am able to navigate to the Category.vue component using <router-link :to = "{ name: 'category', params: { id: id }}"> wh ...

Is WebStorm with Node Supervisor being utilized to eliminate the need for restarting after every code modification?

Currently, I am utilizing WebStorm as my node IDE and have found it to be quite impressive. However, one issue I am facing is figuring out how to incorporate node supervisor into my workflow within WebStorm. Has anyone successfully managed to set this up ...

The Photoswipe default user interface cannot be located

While attempting to incorporate PhotoSwipe into my website, I encountered an uncaught reference error related to The PhotoswipeUI_Default is not defined at the openPhotoSwipe function Below is the code snippet that I have been working on: <!doctyp ...

Managing an Angular timer: Starting and resetting it via the controller

Is there a way to start a timer when the user clicks on the recordLogs method and reset the timer when the user clicks on the stopLogs method? According to the angular-timer documentation, we should be able to use the timer-stop and timer-clear methods to ...

adjust back side height of flip box does not function on IE web browser

I'm currently working on flipping a div/box, and while it's functioning correctly, I'm facing an issue with the height of the back side exceeding that of the front side. This causes the flipped div to always push down to the next element (e. ...

Merging Vue props with v-for for powerful data handling

Below is an example of my child component HTML: <div v-for="(input, index) in form.inputs" :key="index"> <div> <input :name"input.name" :type="input.type" /> </div> </div> JavaScript (Vue): <script> export d ...

Type the query into the search bar on the website, hit the submit button, and receive the search results

Is there a way to dynamically pass any query string (from any oracle table, not hardcoded) from a webpage form/field to the database and have the webpage display a table/grid of the results without predefining columns or table names? Current examples I&apo ...

Organizing outcome searches through ajax

I have a result table displayed on the left side https://i.stack.imgur.com/otaV4.png https://i.stack.imgur.com/pp9m0.png My goal is to transform it into the format shown on the right side of the table In a previous inquiry found here, @Clayton provided ...

What is the process for updating parameters before finalizing a route in Vue.js?

I have set up a route with a value parameter: routes.push({ name: 'test', path: '/test/:value', component: resolve(__dirname, 'src/pages/test.vue'), }); Now, I want to modify the route so that it also include ...

I encountered an issue where the data I passed to a component ended up being undefined

So here's the scenario: I'm working on a Next.js project where I have a context for modals. In this context, I store modal details in an array called modalBase. Additionally, I fetch data from another context (toolsContext) to pass it to componen ...

Ways to send distinct values to updateMany $set in mongodb

I have encountered an issue while trying to generate unique passwords for each document in a MongoDB collection. The current function I am using, however, generates the same password for every user. Below is the code snippet that I am working with: func ...

Submit form data asynchronously using Ajax and serialize the form data before posting

I'm currently facing an issue with posting HTML form values in my code. Everything works fine except for the fact that I can't get it to post single quotes ' . I believe this problem is caused by the usage of serialize. I've attempted c ...