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

Saving a local JSON file in Angular 5 using Typescript

I am currently working on developing a local app for personal use, and I want to store all data locally in JSON format. I have created a Posts Interface and an array with the following data structure: this.p = [{ posts:{ id: 'hey man&ap ...

One way to change the cursor CSS property is by dynamically altering it based on scrolling behavior. This involves modifying the cursor property when scrolling

I'm attempting to adjust the cursor property within an Angular function. The issue I'm facing is that when I begin scrolling the webpage, the cursor changes to a pointer, but when I stop scrolling, it remains as a pointer. I've attempted to ...

Directive for Angular 2: Expand Further

Looking to create a custom readmore directive in Angular2 that will collapse and expand long blocks of text based on a specified max height, rather than character count. The directive will include "Read more" and "Close" links. <div read-more [maxHeigh ...

Versions of Angular that are compatible with Ionic 2 (do not have an exported member)

How do I determine the compatible Angular version for each Ionic version? I keep encountering errors like "has no exported member." For example: The module ".../node_modules/@angular/core/index" does not have an exported member called InjectionToken. The ...

Put Angular4 (Angular) that has been developed with angular-cli onto Google App Engine

After creating an Angular4 application using Angular-CLI, I was able to run it locally with "ng serve" and everything worked perfectly. Now my goal is to deploy it to Google App Engine, where ng build --prod compiles all files into a dist folder. My quest ...

React: Why aren't class methods always running as expected?

I created a class component that retrieves a list of applications from an external API. It then sends a separate request for each application to check its status. The fetching of the applications works well, but there is an issue with the pinging process ...

Ways to Execute the Constructor or ngOnInit Multiple Times

Here's the scenario I'm facing: I have developed an app with multiple screens. One of these screens displays a list of articles. When a user clicks on an article, they are directed to another screen that shows the details of that specific item. ...

The function in Angular 5/Typescript disappears when attempting to call it from within another function

After importing D3 into my component, I encounter an issue when trying to assign a layout to the D3.layout property. Strangely, although the layout property is present in the console output of my D3 object, it seems to be unknown when I attempt to call i ...

How can I utilize npm with the original source code instead of minified or bundled code?

I am looking to access npm and JavaScript (or TypeScript) 3rd party libraries directly from the source code. Similar to how I can make changes in Python libraries by going into their source code, I want to have the same capability with my JavaScript depen ...

Syntax highlighting in VSCode does not seem to be functional when the ?? nullish coalescing operator is being utilized

Hello there! I've recently started using react.js with typescript on a new computer, but I've encountered an issue with syntax highlighting in VSCode. It seems that the problem arises when there's a double question mark (??) in the code, spe ...

When trying to install my npm package from the registry, I keep encountering an issue despite being able to install it locally

I recently released my Node.js/typescript package on the npm registry, but I'm encountering issues when trying to install it from there. Oddly enough, local installation works perfectly fine. Here's the output from the local installation: $ npm ...

What is the best way to declare a collection of objects in TypeScript?

Need assistance with TypeScript - Can anyone help? I'm having trouble deciphering the error message in relation to the code snippet below. My goal is to create an array of objects, but it doesn't seem to be working as expected. interface FieldC ...

Having trouble retrieving information from Node.js service in AngularJS 2

I am currently expanding my knowledge of Angular and attempting to retrieve data from a node js service using Angular 2 services. When I access the node js services directly from the browser, I can see the results. However, when I attempt to fetch the dat ...

Best location for Angular PWA update handler?

Running a PWA app led me to think about decluttering the application.component. To achieve this, I created a dedicated service to monitor PWA updates and alert the user: import { Injectable } from '@angular/core'; import { MatSnackBar } from &qu ...

Check the type of the indexed value

I need help with a standard interface: interface IProps<T> { item: T; key: keyof T; } Is there a way to guarantee that item[key] is either a string or number so it can be used as an index for Record<string | number, string>? My codeba ...

The type 'string | undefined' cannot be assigned to type 'string'

I am facing a challenge in comparing two arrays, where one array is sourced from a third-party AWS service and its existence cannot be guaranteed. Despite my efforts to handle potential errors by incorporating return statements in my function calls, I con ...

Is there a method to ensure the strong typing of sagas for dispatching actions?

Within redux-thunk, we have the ability to specify the type of actions that can be dispatched enum MoviesTypes { ADD_MOVIES = 'ADD_MOVIES', } interface AddMoviesAction { type: typeof MoviesTypes.ADD_MOVIES; movies: MovieShowcase[]; } typ ...

Linking to a variable that could potentially be non-existent

How can I properly bind to myVariable even if it may not be present? (myVariable comes from a service that may not always be active) <input pInputText type="text" [size]="size" [value]="myVariable" style="cursor: poin ...

What is the process for incorporating a new index signature into a class declaration from a file.d.ts in typescript?

I am facing an issue with a class in my project: // some npm module export class User { fname: string; lname: string; } Unfortunately, I cannot modify the declaration of this class from my project root since it is an npm module. I wish to add a new in ...

A TypeScript utility type that conditionally assigns props based on the values of other properties within the type

There is a common need to define a type object where a property key is only accepted under certain conditions. For instance, consider the scenario where a type Button object needs the following properties: type Button = { size: 'small' | &apo ...