I am new to typescript. I have a map in typescript like below:
const mapping = new Map<string, string>();
mapping.set('fruit', 'apple')
mapping.set('vegetable', 'onion')
...
I am trying to convert mapping to type '{ [key: string]: string; }'
How to do that in typescript?
CodePudding user response:
Simply do:
Object.fromEntries(mapping)
Reference:
const mapping = new Map<string, string>()
mapping.set('fruit', 'apple')
mapping.set('vegetable', 'onion')
console.log(mapping)
// { [key: string]: string } is same as Record<string, string>
const record: { [key: string]: string } = Object.fromEntries(mapping)
console.log(record)
CodePudding user response:
You can define an empty object with the new mapping.
Use the Map forEach()
to iterate over the keys.
const mapping = new Map<string, string>();
mapping.set('fruit', 'apple')
mapping.set('vegetable', 'onion');
mapping.set('meat', 'chicken');
mapping.set('drink', 'beer');
console.log(mapping);
const newMapping : { [key : string] : string} = {};
mapping.forEach((val,key) => {
newMapping[key] = val;
});
console.log(newMapping);