Can a map key value be converted into a param object?

I have a map containing key-value pairs as shown below:

for (let controller of this.attributiFormArray.controls) {
     
    attributiAttivitaMap.set(controller.get('id').value,  { value: controller.get('valoreDefault').value, mandatory: controller.get('obbligatorio').value })
}

After setting the values in my map, it looks like this:

0 : key: 10, value: {value: 200, mandatory: false}
1 : key: 102, value: {value: 300, mandatory: false}

Now, my goal is to create a list of objects in the following format:

"valoriDefaultAttributiAttivita" : {
    "10" : {"value" : "200", "mandatory": false},
    "102" : {"value" : "300", "mandatory": false},

 }

where "10" and "102" are the keys from my map.

I've attempted various methods, but when I try to convert it into an array, I struggle to set the key value as a property. Any suggestions on how I can achieve this?

let array: any[] = [];
for(let key of attributiAttivitaMap.keys()){
    array.push({key: attributiAttivitaMap.get(key)});
}

Answer №1

If you want to convert the map into a JavaScript object, you can use the following code:

const map = new Map<number, { value: number; mandatory: boolean }>();

map.set(10, { value: 200, mandatory: false });
map.set(102, { value: 300, mandatory: false });

const obj: Record<number, { value: number; mandatory: boolean }> = {};

map.forEach((val, key) => obj[key] = val);

You can also iterate through the map entries like this:

for(const [key, value] of map.entries()) {
  obj[key] = value;
}

Click here for Playground link

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

Setting up an nginx configuration that seamlessly integrates an Angular 4 application and a WordPress blog within the same route

Presumption: The current system is hosted on https://example.com [which is statically served from /home/centos/projects/dist.example.com] My attempt was to set up the path https://example.com/blogs to run a WordPress blog application. This is my conf ...

How can I apply styling to Angular 2 component selector tags?

As I explore various Angular 2 frameworks, particularly Angular Material 2 and Ionic 2, I've noticed a difference in their component stylings. Some components have CSS directly applied to the tags, while others use classes for styling. For instance, w ...

Using Typescript: Including an additional argument

While experimenting with the code provided in the documentation interface Point { x: number; y: number; } function getX(p: Point) { return p.x; } class CPoint { x: number; y: number; constructor(x: number, y: num ...

Leveraging Javascript Modules within a Typescript Vue Application

The issue at hand I've encountered a problem while attempting to integrate https://github.com/moonwave99/fretboard.js into my Vue project. My initial approach involved importing the module into a component as shown below: <template> <div&g ...

The use of 'import ... =' is restricted to TypeScript files

Error: Oops! Looks like there's a hiccup in the code... 'import ... =' is exclusive to TypeScript files. Expecting '=' here. Don't forget the ';'. Unexpected keyword or identifier popping up! package.json ...

Web performance issues noticed with Angular 8 and Webpack 3.7 rendering speed

My web application is currently taking 35 seconds to render or at least 1.15 seconds from the initial Webpack start. I've made efforts to optimize Webpack, which has improved the launch speed, but the majority of time is consumed after loading main.j ...

Expanding the property of an established type to a nested type

Let's talk about titles. Well, maybe not this one. I tried to come up with a good title, but it didn't work out as planned. In my coding journey, I have created a cool interface called DefaultTheme: export interface DefaultTheme { colors: ...

How can Angular HttpClient be used to convert from Http: JSON.parse(JSON.stringify(data))._body?

When using the Http module, you can use this method: Http service: let apiUrl = this.apiUrl + 'login'; let headers = new Headers({'Content-Type': 'application/json'}); return this.http.post(apiUrl, JSON.stringify(model), {h ...

The issue arises when using Angular Material as it seems that passing a data object to a matdialog dialog

After reviewing multiple posts and carefully examining the process of passing data from an Angular Component to MatDialog, I am facing an issue where 'undefined' is being returned when the dialog loads. Below is the code snippet I have been work ...

Guide on utilizing TypeScript interfaces or types in JavaScript functions with vscode and jsdocs

Is there a way to utilize types or interfaces to provide intellisense for entire functions or object literals, rather than just function parameters or inline @type's? For example: type TFunc = ( x: number ) => boolean; /** * @implements {TFunc} ...

Transmitting language codes from Wordpress Polylang to Angular applications

I am currently attempting to manage the language settings of my Angular application within WordPress using WordPress Polylang. To achieve this, I have set up the following structure in my Angular application: getLanguage.php <?php require_once(". ...

typescript: exploring the world of functions, overloads, and generics

One interesting feature of Typescript is function overloading, and it's possible to create a constant function with multiple overloads like this: interface FetchOverload { (action: string, method: 'post' | 'get'): object; (acti ...

Choosing everything with ngrx/entity results in not selecting anything

Issue with Selector I am facing an issue with my selector in the component. Despite making the call, the component does not update with books from the FakeApiService. The actions and effects seem to be functioning correctly. The problem seems to be relat ...

Learn how to utilize React lazy effectively in components that utilize Redux compose without any similarities to type 'IntrinsicAttributes'

Here is the structure of a component that is exported with compose from redux. This component is called TestInspector.tsx export interface TestInspectorProps { closeInspector: () => void; onExpand: () => void; isFullScreen: boolean; selected ...

Why is the data from an Angular service returning as undefined when I call it from a component?

Currently, I'm utilizing the JSONPlace holder Fake API to retrieve data. Despite successfully fetching the data in my service, when I attempt to call that service from my app component, I am encountering an issue where it returns undefined. What could ...

Is it possible to utilize a mat-checkbox in place of a mat-label?

I'm attempting to build a mat-form-field with a checkbox that, when checked, will enable the form field. I believe this can be achieved through CSS adjustments, but I wonder if there is a simpler solution that I might be overlooking. <mat-f ...

Ways to organize JSON information in Angular by date basis?

I am working on a project where I need to organize multiple JSON objects into an array based on their date data, with the date field serving as the key. ...

Issue: The method spyOn cannot be used on the fromEvent function because it is either not writable or does not have a setter defined

After transitioning our codebase from rxjs v5.5.12 to rxjs v6.4.0, we encountered an error when running a test case. Old Code: import * as ObservableEvents from 'rxjs/Observable/fromEvent'; spyOn(ObservableEvents, 'fromEvent').and.ret ...

Minimize the quantity of data points displayed along the X-axis in a highcharts graph

After making an API call, I received data for a Highcharts graph consisting of an array of datetimes (in milliseconds) and corresponding values (yAxis). The data is fetched every 15 minutes and displayed on a mobile device. When viewing the data monthly, ...

What are the best ways to personalize my code using Angular Devextreme?

Our development team is currently utilizing Angular for the front-end framework and ASP.net for the back-end framework. They are also incorporating Devextreme and Devexpress as libraries, or similar tools. However, there seems to be difficulty in implement ...