What is the Map.entries() method in TypeScript?

Overview

In TypeScript, a Map is a data structure used to hold key-value pairs of any datatype. The entries() method of the Map class returns an iterator with key-value pairs.

Syntax

let mapObject = new Map()
mapObject.entries()
Syntax for Map entries() method in TypeScript

Parameters

This method takes no parameters.

Return value

This method returns an iterator for all the key-value pairs inserted in the Map object.

Note: The returned iterator iterates the key-value pairs in the order of their insertion.

Example

// create some Maps
let evenNumbers = new Map<string, number>([["two", 2], ["four", 4], ["eight", 8]])
let cart = new Map<string, number>([["rice", 500], ["bag", 10]])
let countries = new Map<string, string>([["NG", "Nigeria"], ["BR", "Brazil"], ["IN", "India"]])
let isMarried = new Map<string, boolean>([["James", false], ["Jane", true], ["Doe", false]])
let emptyMap = new Map<null, null>()
// get the iterators for all Maps
let itr1 = evenNumbers.entries()
let itr2 = cart.entries()
let itr3 = countries.entries()
let itr4 = isMarried.entries()
let itr5 = emptyMap.entries()
// print out the iterators
console.log(itr1)
console.log(itr2)
console.log(itr3)
console.log(itr4)
// print out the entries for any of the iterators
for (let entry of itr1) {
console.log(entry);
}

Explanation

  • Lines 2–6: We create five Map objects in TypeScript.
  • Lines 9–13: We use the entries() method to get the iterators for each Map object.
  • Lines 16–19: We print the iterators to the console.
  • Lines 22: We print the key-value pairs in itr1 one by one using the for of loop.

Free Resources