-1

I am getting a data of type ANY from the backend c# in angular .

It is coming in the form of object .

I want to convert this object into a type of Map<string, string[]>(); in Angular , so that i get VA as the key , and the 3 strings as the value .

Can anyone help me with this please ?

2 Answers2

1

If you have an object, regardless of type, that is:

const obj: any = {
  $id: "1",
  VA305: ["0000034", "8008200", "0000000"],
}

All that's required to convert that into a map is just:

const yourMap: Map<string, string[]> = new Map();
const key = 'VA305';

map.set(key, obj[key]);

If you need to set a map value for each key in the object, or only certain keys in a loop, you can do that too:

const keys: string[] = Object.keys(obj);
const yourMap: Map<string, string[]> = new Map();

keys.forEach(key => {
  if (key !== '$id') {
    map.set(key, obj[key])
  }
});
Brandon Taylor
  • 33,823
  • 15
  • 104
  • 144
1

Here is a wroker function you can use:

function buildMap(obj: any) {
    let map = new Map();
    Object.keys(obj).forEach(key => {       
        map.set(key, obj[key]);
    });
    return map;
}

For more options please see answers in this SO: How to convert a plain object into an ES6 Map?

Enjoy!

DavidDr90
  • 559
  • 5
  • 20