Skip to content

JavaScript:Map

TypeScript Signature

// ES2015
interface Map<K, V> {
    clear(): void;
    delete(key: K): boolean;
    forEach(callbackfn: (value: V, key: K, map: Map<K, V>) => void, thisArg?: any): void;
    get(key: K): V | undefined;
    has(key: K): boolean;
    set(key: K, value: V): this;
    readonly size: number;
}

interface Map<K, V> {
    /** Returns an iterable of entries in the map. */
    [Symbol.iterator](): IterableIterator<[K, V]>;

    /**
     * Returns an iterable of key, value pairs for every entry in the map.
     */
    entries(): IterableIterator<[K, V]>;

    /**
     * Returns an iterable of keys in the map
     */
    keys(): IterableIterator<K>;

    /**
     * Returns an iterable of values in the map
     */
    values(): IterableIterator<V>;
}

Simple example

let people = new Map<string, Person>();

It supports the same functionality as Object, and more, with a slightly different syntax:

// Adding an item (a key-value pair):
people.set("John", { firstName: "John", lastName: "Doe" });

// Checking for the presence of a key:
people.has("John"); // true

// Retrieving a value by a key:
people.get("John").lastName; // "Doe"

// Deleting an item by a key:
people.delete("John");

Convert Map to json

export class RoiInfoDictionary {
  elems: Map<string, RoiInfo>;

  constructor(json?: string) {
    this.elems = new Map<string, RoiInfo>();
    if (json) {
      this.fromJson(json);
    }
  }

  toJson(): string {
    let jsonObject = {};
    this.elems.forEach((value, key) => {
      jsonObject[key] = value;
    });
    return JSON.stringify(jsonObject);
  }

  fromJson(json: string): void {
    let jsonObject = JSON.parse(json);
    this.elems.clear();
    for (const value in jsonObject) {
      this.elems.set(value, jsonObject[value]);
    }
  }
}

See also

Favorite site