travis_91
travis_91

Reputation: 173

Is it possible to transform a key value from a map in a param object?

I have a map in which I put a key value like this:

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

and this is my map after the set:

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

Ok now my porpuse is to create a list of object like this:

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

 }

where the numbers "10", "102" are the keys of my map.

I tried in several ways but when I try to put it in array for example it doesn't allow me to set my value of key like a property.

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

How I can do this?

Upvotes: 1

Views: 437

Answers (1)

Temoncher
Temoncher

Reputation: 704

If your goal is to get the same map but in form of js object, you can do following

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);

Or iterate through map entries

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

Playground link

Upvotes: 2

Related Questions