Map.entries()
The Map.entries()
method in JavaScript returns an iterator object that contains all key-value pairs of a Map
in insertion order. Each entry is represented as an array [key, value]
.
Syntax
</>
Copy
map.entries()
Parameters
The entries()
method does not take any parameters.
Return Value
The method returns a new Map Iterator
object that yields key-value pairs as arrays [key, value]
in insertion order.
Examples
1. Retrieving All Entries from a Map
This example demonstrates how to retrieve key-value pairs from a Map
using entries()
.
</>
Copy
const map = new Map();
map.set('a', 1);
map.set('b', 2);
map.set('c', 3);
const iterator = map.entries();
console.log(iterator.next().value);
console.log(iterator.next().value);
console.log(iterator.next().value);
Output
["a", 1]
["b", 2]
["c", 3]
2. Iterating Over a Map Using entries()
The entries()
method is commonly used with a for...of
loop to iterate over key-value pairs in a Map
.
</>
Copy
const map = new Map([
['name', 'Arjun'],
['age', 25],
['city', 'New York']
]);
for (const [key, value] of map.entries()) {
console.log(`${key}: ${value}`);
}
Output
name: Arjun
age: 25
city: New York
3. Converting a Map to an Array
Since entries()
returns an iterable, you can convert it into an array using Array.from()
.
</>
Copy
const map = new Map([
['x', 10],
['y', 20],
['z', 30]
]);
const entriesArray = Array.from(map.entries());
console.log(entriesArray);
Output
[
["x", 10],
["y", 20],
["z", 30]
]
4. Using entries()
with Object.fromEntries()
The entries()
method can be used with Object.fromEntries()
to convert a Map
into a plain JavaScript object.
</>
Copy
const map = new Map([
['id', 101],
['title', 'Developer'],
['salary', 5000]
]);
const obj = Object.fromEntries(map.entries());
console.log(obj);
Output
{
id: 101,
title: "Developer",
salary: 5000
}