Skip to content

toObject()

ts
function toObject<K, V>(this): Record<PropertyKey, V> | null;

Defined in: map/to-object.ts:33

Converts a Map (or ReadonlyMap) into a plain object whose properties correspond to the Map’s keys and values. If the M̀ap is empty, or if it yields no enumerable keys after conversion, null is returned instead of an empty object.

Type Parameters

Type Parameter
K extends PropertyKey
V

Parameters

ParameterTypeDescription
thisReadonlyMap<K, V>Map instance

Returns

Record<PropertyKey, V> | null

A Record<PropertyKey, V> with the same key-value pairs as the Map. Or null if the Map is empty or the resulting object has no own enumerable keys.

Example

ts
const mapTest = new Map();

const sym = Symbol()

mapTest.set("name", "John");
mapTest.set(1, 1);
mapTest.set(sym, { test: "hello" });

const object = mapTest.toObject();

const expectedResult = {
  name: "John",
  1: 1,
  [sym]: { test: "hello" }
}

console.assert(JSON.stringify(expectedResult) === JSON.stringify(object));

Since

1.0.0

Author

Ian Wenneckers