Convert to a TypeScript map

Here are the configurations I am working with:

type Choice = {
  value: any,
  label: any
}

Additionally, there is a role interface:

export interface UserRole {
  id: number
  name: string
}

I have a set of roles:

const userRoles:UserRole[]:[
{id:1,name:'name1'},
{id:2,name:'name2'},
{id:3,name:'name3'}
]

My goal is to extract Choices[] from this set of roles. How can I achieve this in javascript?

In java, I could use the following code snippet:

roles.stream().map(role->new Choice(role.id,role.name)).collect(collectors.toList());

Answer №1

You have the option to simply use the map() function to transform roles into options:

type Option = {
  value: any;
  label: any;
}

interface Role {
  id: number;
  name: string;
}

const roles: Role[] = [
  {id: 1, name: 'name1'},
  {id: 2, name: 'name2'},
  {id: 3, name: 'name3'}
];

const options: Option[] = roles.map(({id, name}) => ({value: id, label: name}));

Link to playground

Answer №2

Javascript Playground link

type Option = {
  value: any,
  label: any
}

interface Role {
  id: number
  name: string
}

const roles: Role[] = [
  { id: 0, name: "foo" },
  { id: 1, name: "bar" },
  { id: 2, name: "baz" },
]

const result: Option[] = roles
  .map(({ id, name }) => ({ label: id, value: name }));

console.log(result);

Result:

[LOG]: [{
  "label": 0,
  "value": "foo"
}, {
  "label": 1,
  "value": "bar"
}, {
  "label": 2,
  "value": "baz"
}]

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

Innovative idea for a time management system based on timelines and scheduling

My latest project involves creating a scrollable scheduler, inspired by vis-timeline and built using Vue.js. One of the main challenges I'm facing is achieving smooth infinite scrolling in all directions (past and future). I must confess that I&apo ...

Conditionals in ng-class Syntax

I'm attempting to apply a class conditionally to an element, but I'm struggling with the correct syntax. I've experimented with the code below, but it's not functioning as expected: ng-class="{foo: bar === "true"}" The value of bar i ...

Why does ASP.NET sometimes set my JavaScript object to null?

There is a <script> in my code that includes the following line: var tbl = document.getElementById("<%= this.tblSelection.ClientID %>"); Despite this, when the script runs, tbl always ends up being set to null. The table has been defined lik ...

Is there a way to merge these arrays into a single array?

With the current code I am obtaining numerous JSON objects within separate arrays: Here is the code snippet: for (let i=1; i<=150;i++){ fetch(`A valid URL ${i}`) .then(result => result.json()) .then(result => console.log(result.data.results)) ...

How to add 1 to the final element in a JavaScript

I'm currently working on a task that involves incrementing the last element in an array using pop() and push(). However, I'm facing an issue where the original values are being retained after I try to increment the popped array. The objective is ...

JS faces a challenge when it comes to functional programming

Experimenting with bind, call, and apply, I am exploring updating object properties by passing function return values to object methods. This updating is triggered by the window resize event. var el = document.getElementById('someElement'); ...

Error: Angular version 15 is unable to locate the module '@env/environment' or its corresponding type declarations

Recently, I developed an Angular 15 application with the environments folder located under src. Here is a snippet from my tsconfig.json file: "baseUrl": "./src", "paths": { "@app/*": [ "app/*" ], "r ...

The JSON.stringify method may not accurately reflect the original object that was converted into a string

Working on a Connect Four app for my school project has been an interesting challenge. At the moment, I am grappling with JSON.stringify and trying to encode an object that holds a two-dimensional array of "hole" objects to eventually send it to the server ...

I'm trying to showcase an array list in React, but for some reason it's not appearing on the screen even though I believe I've followed all the necessary

I am trying to show a list of items from an array in React, but for some reason it's not displaying. I believe I have done everything correctly, so where did I go wrong? Here is the code: import { useState } from 'react'; function App() { ...

Transferring a two-dimensional array from Fortran to C

I've encountered some challenges when trying to pass a 2d array from Fortran to a C function. However, with the help and support I received, the code below is now functioning perfectly. Here is the C function: #include <stdio.h> void print2( ...

The process of incorporating content from a different page into a Bootstrap 5 Modal can be achieved by using Laravel 10

Here is a snippet of my code from index.blade.php: <a data-bs-toggle="modal" data-bs-target="#modal_frame" href="{{route('caborCreate')}}">link</a> This is how the modal is coded in the create page - cre ...

Identifying content loading in ajax div

I am currently utilizing the ajaxpage feature from the code offered by Dynamic Drive (). My goal is to have the original page, which sent the ajax content request to the div, recognize when the div has finished loading. Here are the methods I have experi ...

Tips for incorporating auth0 into a vue application with typescript

Being a beginner in TypeScript, I've successfully integrated Auth0 with JavaScript thanks to their provided sample code. However, I'm struggling to find any sample applications for using Vue with TypeScript. Any recommendations or resources would ...

Create a "Line" on the canvas by adjusting the attributes of the "Line" object using Three.JS

I have successfully created a cube and lines using Three.js. My goal is to position the lines around the cube as guidelines, as shown below: However, I am struggling to understand the properties of the line: var lengthVertArray = lengthLineGeometry.vert ...

Directing to index.html using ExpressJS

JS, I am working on an express app that has various routes defined. However, I am facing an issue where if the router does not match any route, it displays index.html instead of redirecting to a specific route like '/*' as I expected. I am unsu ...

Assigning union values to an object array: a guide for Typescript

When working with union typed values in an object array, how should the setState() function be implemented? enum SomeStateEnum { IsRunning, Name, } type PersonState = { [SomeStateEnum.IsRunning]: boolean; [SomeStateEnum.Name]: string; }; const st ...

Using Selenium Webdriver to target and trigger an onclick event through a CSS selector on a flight booking

I've been running an automation test on the website . When searching for a flight, I encountered an issue where I was unable to click on a particular flight. I initially tried using Xpath but it wasn't able to locate the element when it was at th ...

XMLHttp request experiencing mixed content issues

Struggling with obtaining OAuth Tokens from a POST request through the Bungie API using javascript and XMLHttpRequest. Despite both my website and the API endpoint being secure (https), every post request I send returns a Mixed Content page error. I'v ...

Receive a distinct key alert after including a key attribute to a div element containing multiple sub nodes in react version 18.2.0

When attempting to render the div element on the page, I encountered a warning stating: "Each child in a list should have a unique 'key' prop." <div {...{}} key={"formKey"}> <input type="text" /> <button> ...

Exploring the power of regular expressions in Javascript when used between

Consider the scenario outlined in the text below I desire [this]. I also desire [this]. I do not desire \[this] I am interested in extracting the content enclosed within [], but not including \[]. How should I approach this? Currently, I have ...