Typescript Map throwing error while using its functions (mapobject.keys() is not a function)
Asked Answered
A

2

14

I am a new bee in typescript , In my angular4 project I am receiving a map object as a json.

so I declared a class that is given bellow

 <importing... required classes here..>
  export class FormConfig  {
    public id: number;
    public name: string;
    public fieldMap :Map<string,Array<Field>>;
    public fieldList : Array<Field> ;
  }

I am receiving exactly same JSON from api. I consoled the object of FormConfig and I am getting the console without any error. My code got compiled without any warning and error. But I can't access the keys and values from the map by using Map's inbuilt functions like forEach,keys,get etc. But IDE showing these function suggestions. Part of my code is given bellow.

 formConfig : FormConfig; 
 console.log(JSON.stringify(formConfig)); // works fine

 keys : string [] = Array.from (formConfig.keys()) ; // showing error (formConfig.keys is not a function)

I am using es5 target for my angular4 project and the IDE is visual studio code.

Is anybody faced this issue before let me know the mistake I have made here.

Thank you.

Aleishaalejandra answered 21/7, 2017 at 10:13 Comment(7)
I think you are not using keys on the right way Object.keys(obj), obj The object of which the enumerable own properties are to be returned.Yahwistic
I tried foreach , that is also not workingAleishaalejandra
Did you try keys : string [] = Object.keys(formConfig) ?Yahwistic
Yes your code works. Thank you very much , I want to get the value alsoAleishaalejandra
Does typescript support Map ?Aleishaalejandra
What you want to get? Array of keys and another array of the values?Yahwistic
I just want keys array and the values array, I just wanna get value by using keyAleishaalejandra
Y
17

You can get the values using key like this:

for (const key in formConfig) {
  console.log('The value for ' + key + ' is = ' + formConfig[key]);
}

And getting array of the Object's key values is done like this:

keys: string [] = Object.keys(formConfig);
Yahwistic answered 21/7, 2017 at 10:46 Comment(2)
Thank you very much man.. but why this get, foreach and keys function not working ? do you have any idea ?Aleishaalejandra
If you want to use foreachyou have to have map Map.prototype.forEach(), but in your case it's Object and for that you use for .. inYahwistic
A
0

The keys() method from the Object class can be used instead of writing the a manual for loop.

keys: string[] = Object.keys(formConfig);
Aswan answered 10/11, 2021 at 13:49 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.