Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to convert Map<string,boolean> to {key: string; value: boolean;}[]?

I’m using React with TypeScript support and on the user creation page, I have implemented the dynamic creation of permissions, following this peace of code.
The permissions used on the page are set by the following hook:

const [permissions, setPermissions] = useState<{ perm: string; isTrue: boolean; }[]>([]);

The interface IUser, however, has permissions specified as follows:

export interface IUser {
    permissions: Map<string, boolean>
}

How can I convert Map<string, boolean> type to { perm: string; isTrue: boolean; }[]?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

I’ve tried using Map.prototype.forEach() and Map.prototype.entries(), but couldn’t figure out how to bring their results to the right type.

I also know that the reverse conversion can be done using the following trick, but not sure if it can be used the other way around.

>Solution :

You can use Array.from() with a custom map callback function parameter that destructures each Map item into its key (=perm) and value (=isTrue) and creates a new object from that.

export interface IUser {
  permissions: Map<string, boolean>;
}

declare const permissionsMap: Map<string, boolean>;

const permissionsArray = Array.from(permissionsMap, ([perm, isTrue]) => ({
  perm,
  isTrue,
}));
// const permissionsArray: { perm: string; isTrue: boolean; }[]

TypeScript Playground

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading