Chuyển tới nội dung
Home » Js Map On Object | Description

Js Map On Object | Description

Use Maps more and Objects less

When to use Map and Object

Map have higher performance and require less code to write, giving them an advantage over Object.

The following are some cases where you can use Map:

  • If you want to use complex data types as keys.
  • If preserving the insertion order of your keys is required.
  • When performing hashing.

However, some cases necessitate the use of an Object. The following are some of them:

  • Object is ideal for cases where we need a simple structure to hold data and the keys are either strings or symbols.
  • Object is unquestionably the best option in scenarios where different logic must be applied to each property piece.
  • When dealing with JSON data, Object have direct support in JSON, but Map do not.

Map.values()

The

values()

method returns an iterator object with the values in a Map:

Example

let text = “”;

for (const x of fruits.values()) {

text += x;

You can use the

values()

method to sum the values in a Map:

Example

let total = 0;

for (const x of fruits.values()) {

total += x;

Use Maps more and Objects less
Use Maps more and Objects less

Examples

Using the Map object


const myMap = new Map(); const keyString = "a string"; const keyObj = {}; const keyFunc = function () {}; // setting the values myMap.set(keyString, "value associated with 'a string'"); myMap.set(keyObj, "value associated with keyObj"); myMap.set(keyFunc, "value associated with keyFunc"); console.log(myMap.size); // 3 // getting the values console.log(myMap.get(keyString)); // "value associated with 'a string'" console.log(myMap.get(keyObj)); // "value associated with keyObj" console.log(myMap.get(keyFunc)); // "value associated with keyFunc" console.log(myMap.get("a string")); // "value associated with 'a string'", because keyString === 'a string' console.log(myMap.get({})); // undefined, because keyObj !== {} console.log(myMap.get(function () {})); // undefined, because keyFunc !== function () {}

Using NaN as Map keys


NaN

can also be used as a key. Even though every

NaN

is
not equal to itself (

NaN !== NaN

is true), the following example works because

NaN

s are indistinguishable from each other:


const myMap = new Map(); myMap.set(NaN, "not a number"); myMap.get(NaN); // "not a number" const otherNaN = Number("foo"); myMap.get(otherNaN); // "not a number"

Iterating Map with for…of

Maps can be iterated using a

for...of

loop:


const myMap = new Map(); myMap.set(0, "zero"); myMap.set(1, "one"); for (const [key, value] of myMap) { console.log(`${key} = ${value}`); } // 0 = zero // 1 = one for (const key of myMap.keys()) { console.log(key); } // 0 // 1 for (const value of myMap.values()) { console.log(value); } // zero // one for (const [key, value] of myMap.entries()) { console.log(`${key} = ${value}`); } // 0 = zero // 1 = one

Iterating Map with forEach()

Maps can be iterated using the

forEach()

method:


myMap.forEach((value, key) => { console.log(`${key} = ${value}`); }); // 0 = zero // 1 = one

Relation with Array objects


const kvArray = [ ["key1", "value1"], ["key2", "value2"], ]; // Use the regular Map constructor to transform a 2D key-value Array into a map const myMap = new Map(kvArray); console.log(myMap.get("key1")); // "value1" // Use Array.from() to transform a map into a 2D key-value Array console.log(Array.from(myMap)); // Will show you exactly the same Array as kvArray // A succinct way to do the same, using the spread syntax console.log([...myMap]); // Or use the keys() or values() iterators, and convert them to an array console.log(Array.from(myMap.keys())); // ["key1", "key2"]

Cloning and merging Maps

Just like

Array

s,

Map

s can be cloned:


const original = new Map([[1, "one"]]); const clone = new Map(original); console.log(clone.get(1)); // one console.log(original === clone); // false (useful for shallow comparison)

Note: Keep in mind that the data itself is not cloned.

Maps can be merged, maintaining key uniqueness:


const first = new Map([ [1, "one"], [2, "two"], [3, "three"], ]); const second = new Map([ [1, "uno"], [2, "dos"], ]); // Merge two maps. The last repeated key wins. // Spread syntax essentially converts a Map to an Array const merged = new Map([...first, ...second]); console.log(merged.get(1)); // uno console.log(merged.get(2)); // dos console.log(merged.get(3)); // three

Maps can be merged with Arrays, too:


const first = new Map([ [1, "one"], [2, "two"], [3, "three"], ]); const second = new Map([ [1, "uno"], [2, "dos"], ]); // Merge maps with an array. The last repeated key wins. const merged = new Map([...first, ...second, [1, "eins"]]); console.log(merged.get(1)); // eins console.log(merged.get(2)); // dos console.log(merged.get(3)); // three

Useful JavaScript Map methods


  • clear()

    – removes all elements from the map object.

  • delete(key)

    – removes an element specified by the key. It returns if the element is in the map, or false if it does not.

  • entries()

    – returns a new Iterator object that contains an array of

    [key, value]

    for each element in the map object. The order of objects in the map is the same as the insertion order.

  • forEach(callback[, thisArg])

    – invokes a callback for each key-value pair in the map in the insertion order. The optional thisArg parameter sets the

    this

    value for each callback.
  • get(key) – returns the value associated with the key. If the key does not exist, it returns undefined.
  • has(key) – returns true if a value associated with the key exists or false otherwise.

  • keys()

    – returns a new Iterator that contains the keys for elements in insertion order.

  • set(key, value)

    – sets the value for the key in the map object. It returns the map object itself therefore you can chain this method with other methods.

  • values()

    returns a new iterator object that contains values for each element in insertion order.
Maps in Javascript (Map Object)
Maps in Javascript (Map Object)

Browser compatibility

BCD tables only load in the browser

A Map object in JavaScript is a collection of key-value pairs where the keys can be of any type, including objects or functions. Explore how to create and use Map objects, and the differences they bring when compared to regular JavaScript objects.

When working with JavaScript, developers often encounter situations where they need to store and manipulate key-value pairs. While JavaScript objects provide a way to achieve this, Map objects offer additional features and advantages that can simplify and enhance the handling of key-value data.

In this article, we will explore what Map objects are, how to create and use them, and the differences they bring when compared to regular JavaScript objects.

A Map object in JavaScript is a collection of key-value pairs where the keys can be of any type, including objects or functions. It allows efficient storage and retrieval of values based on their associated keys.

Map objects provide a simple and straightforward way to manage data relationships and perform common operations such as adding, removing or updating values associated with specific keys.

To create a new Map object, we can use the

Map()

constructor:


const map = new Map();

In the above code, we create a new Map object named

map

. Initially, this Map object is empty, with no key-value pairs.

Alternatively, we can initialize a Map object with an array of key-value pairs during its creation:


const map = new Map([ ["key1", "value1"], ["key2", "value2"], ["key3", "value3"], ]);

In the above code, we create a Map object

map

with three key-value pairs. The keys are

'key1'

,

'key2'

and

'key3'

, and their corresponding values are

'value1'

,

'value2'

and

'value3'

,
respectively.

Once a Map object has been created, we can use various methods provided by the Map prototype to manipulate its content. Let’s explore some common operations:

To add or update a value associated with a specific key in a Map object, we can use the

set()

method:


const map = new Map(); map.set("key1", "value1"); map.set("key2", "value2"); console.log(map); // Output: Map(2) {'key1' => 'value1', 'key2' => 'value2'}

In the above code, we add two key-value pairs to the Map object

map

. The first pair has the key

'key1'

and the value

'value1'

, while the second pair has the key

'key2'

and the value

'value2'

.
If a key already exists in the Map, the

set()

method will update its corresponding value.


const map = new Map(); map.set("key", "value"); map.set("key", "updated value"); console.log(map); // Output: Map(1) {'key' => 'updated value'}

To retrieve a value from a Map object based on its key, we can use the

get()

method:


const map = new Map([ ["key1", "value1"], ["key2", "value2"], ]); const value = map.get("key1"); console.log(value); // Output: 'value1'

In the above code, we create a Map object

map

with two key-value pairs. We then retrieve the value associated with the key

'key1'

using the

get()

method.

To check if a specific key exists in a Map object, we can use the

has()

method:


const map = new Map([ ["key1", "value1"], ["key2", "value2"], ]); console.log(map.has("key1")); // Output: true console.log(map.has("key3")); // Output: false

In the above code, we create a Map object

map

with two key-value pairs. We then use the

has()

method to check the existence of keys

'key1'

and

'key3'

. The method returns

true

if the key
is found in the Map, and

false

otherwise.

To remove a key-value pair from a Map object, we can use the

delete()

method:


const map = new Map([ ["key1", "value1"], ["key2", "value2"], ]); map.delete("key1"); console.log(map); // Output: Map(1) {'key2' => 'value2'}

In the above code, we create a Map object

map

with two key-value pairs. We then remove the key-value pair with the key

'key1'

using the

delete()

method.

To determine the number of key-value pairs in a Map object, we can use the

size

property:


const map = new Map([ ["key1", "value1"], ["key2", "value2"], ]); console.log(map.size); // Output: 2

In the above code, we create a Map object

map

with two key-value pairs. We then access the

size

property to retrieve the number of pairs in the Map.

While standard JavaScript objects (e.g.,

{}

) are commonly used for key-value storage, Map objects offer several advantages that can make them a better choice in certain scenarios:

Flexible key types: Map objects allow any data type as keys, including objects, functions and primitives, whereas JavaScript objects only allow number, string or symbol keys.

Maintaining insertion order: Map objects preserve the order of key-value pairs as they are inserted, whereas JavaScript objects do not guarantee the order of keys.

Iterating with ease: Map objects provide built-in methods such as

forEach()

and

entries()

to iterate over key-value pairs, making it simpler to work with the data structure.

Efficient size retrieval: Map objects have a dedicated

size

property, allowing quick retrieval of the number of key-value pairs, while JavaScript objects require manual iteration or using the

Object.keys()

method to return an accurate count.

It’s worth noting that if you only need string keys and simple key-value operations, JavaScript objects can still be a suitable choice.

Map objects in JavaScript provide a powerful and flexible way to store and manipulate key-value pairs. With their ability to handle various key types, maintain insertion order and provide convenient iteration methods, Map objects offer advantages over regular JavaScript objects in specific use cases. By understanding how to create and work with Map objects, developers can leverage their features to write more expressive and efficient code.

Hassan is currently a senior frontend engineer at Doordash. Prior to Doordash, Hassan worked at Instacart and Shopify, where he helped build large production applications at-scale. Hassan is also a published author and course instructor and has helped thousands of students learn in-depth fronted engineering tools like React, Vue, TypeScript and GraphQL. Hassan’s non-work interests range widely and, when not in front of a computer screen, you can find him at the gym, going for walks or running through the six.

Subscribe to be the first to get our expert-written articles and tutorials for developers!

All fields are required

We see that you have already chosen to receive marketing materials from us. If you wish to change this at any time you may do so by clicking here.

Summary: in this tutorial, you will learn about the JavaScript Map object that maps a key to a value.

Manipulation of Map and Object

Construction

Map

A Map can be created using the Map constructor in JavaScript.

const map = new Map([[1, “one”], [2, “two”], [3, “three”]]);

We can set the values initially by parsing an array of arrays. The inner arrays contain a key and a value as their elements. The key field in Map can be of any data type such as number, array, or object.

Object

There are many ways to instantiate an Object.

const obj1 = { 1: “one”, 2: “two”, 3: “three” }; const obj2 = new Object({ 1: “one”, 2: “two”, 3: “three” }); const obj3 = Object.create(obj1);

In the example above, obj1 is created using Object literal syntax while the Object constructor is used for obj2. In obj3, we passed an Object that should be the newly created Object prototype. The data type of the key field in Object is limited to strings and symbols. As a result, the keys given as numbers in the above code snippet will be converted to strings internally.

Item manipulation

Map: Get, set, and delete elements

In Map, we have to use the set() method to insert values, the get() method to access elements, and the delete() method to delete elements.

const map = new Map(); map.set(1, “one”); console.log(map.get(1)); // output: one map.delete(1); console.log(map); // Map(0) {}

The set() method requires two parameters to initialize the key and value of a Map element. On the other hand, the get() method returns the value of the key we pass as the parameter. We can delete an element by passing the key to the delete() method.

Object: Dot notation

We can use either dot notation or square bracket notation to access elements in an Object.

const obj = {}; obj.a = “one” obj[“b”] = “two” console.log(obj.a); // output: one console.log(obj[“b”]); //output: two delete obj.a delete obj[“b”] console.log(obj); // output: {}

Dot notation is straightforward, and we can access elements directly by their key. On the other hand, square bracket notation should be used in full when dynamically accessing the element. Also, we can use the delete keyword to delete elements from an Object.

Read keys and values

Map

In Map, we can use the keys() method to get the list of keys in a map.

const map = new Map([[1, “one”], [2, “two”]]); console.log(map.keys()); // output: [Map Iterator] { 1, 2 } console.log(Array.from(map.keys())); // output: [1, 2] console.log(map.values()); // output: [Map Iterator] { ‘one’, ‘two’ } console.log(Array.from(map.values())); // output: [‘one’, ‘two’] console.log(map.entries()); // output [Map Iterator] { [1, ‘one’], [2, ‘two’] } console.log(Array.from(map.entries())); // output [ [1, ‘one’], [2, ‘two’] ]

map.keys() returns a Map Iterator with the keys, while map.values() returns a Map Iterator with values. On the other hand, map.entries() can be used to return a Map Iterator with key-value pairs. We can convert these Map Iterators to arrays using Array.from().

Object

To get the keys to an Object, we can use Object.keys() and Object.values() to get the values, while Object.entries() can be used to get the key-value pairs.

const obj = { 1: “one”, 2: “two” }; console.log(Object.keys(obj)); // output: [‘1’, ‘2’] console.log(Object.values(obj)); // output: [‘one’, ‘two’] console.log(Object.entries(obj)); // output: [ [‘1’, ‘one’], [‘2’, ‘two’] ]

The above functions return an array of keys, values, or key-value pairs of the Object we pass as the parameter.

Check if a key exists

Map

Map have the has() method to check if a key exists.

console.log(map.has(2)); // output: true or false

Object

The following methods can be used to check the existence of a key in an Object.

console.log(2 in obj); // output: true or false console.log(obj.hasOwnProperty(2)); // output: true or false

Get length

Map

We can get the size or the number of elements of a Map using the size property.

console.log(map.size); // output: 2

Object

We can get the size of an Object as shown below.

console.log(Object.keys(obj).length); // output: 2

Here, we got the keys array from the Object and used length to get the number of elements, similar to the Object’s size.

Iteration

Map

There are several ways to iterate over the elements in a Map. The following code example illustrates iterating using for and forEach loops.

//method 1 for (const [ key, value ] of map) { console.log(value); }; //method 2 map.forEach((value, key) => console.log(value));

Object

Similar to Map, Object can also be iterated in many ways. The following code example illustrates iterating using for and forEach loops.

//method 1 for (const [key, value ] of Object.entries(obj)) { console.log(value); }; //method 2 Object.entries(obj).forEach(([ key, value ]) => console.log(value));

Unlike in Map, we need helper functions to access key-value pairs in Object.

Maps vs. Objects in JavaScript - What's the Difference?
Maps vs. Objects in JavaScript – What’s the Difference?

Map.set()

You can add elements to a Map with the

set()

method:

Example

const fruits = new Map();

// Set Map Values

fruits.set(“apples”, 500);

fruits.set(“bananas”, 300);

fruits.set(“oranges”, 200);

The

set()

method can also be used to change existing Map values:

Example

Examples

Using get()


const myMap = new Map(); myMap.set("bar", "foo"); console.log(myMap.get("bar")); // Returns "foo" console.log(myMap.get("baz")); // Returns undefined

Using get() to retrieve a reference to an object


const arr = []; const myMap = new Map(); myMap.set("bar", arr); myMap.get("bar").push("foo"); console.log(arr); // ["foo"] console.log(myMap.get("bar")); // ["foo"]

Note that the map holding a reference to the original object effectively means the object cannot be garbage-collected, which may lead to unexpected memory issues. If you want the object stored in the map to have the same lifespan as the original one, consider using a

WeakMap

.

Map vs Object in JavaScript
Map vs Object in JavaScript

Instance methods


Map.prototype.clear()

Removes all key-value pairs from the


Map

object.


Map.prototype.delete()

Returns


true

if an element in the

Map

object existed and has been removed, or

false

if the element does not exist.

map.has(key)

will return

false

afterwards.


Map.prototype.entries()

Returns a new Iterator object that contains a two-member array of


[key, value]

for each element in the

Map

object in insertion order.


Map.prototype.forEach()

Calls


callbackFn

once for each key-value pair present in the

Map

object, in insertion order. If a

thisArg

parameter is provided to

forEach

, it will be used as the

this

value for each callback.


Map.prototype.get()

Returns the value associated to the passed key, or


undefined

if there is none.


Map.prototype.has()

Returns a boolean indicating whether a value has been associated with the passed key in the


Map

object or not.


Map.prototype.keys()

Returns a new Iterator object that contains the keys for each element in the


Map

object in insertion order.


Map.prototype.set()

Sets the value for the passed key in the


Map

object. Returns the

Map

object.


Map.prototype.values()

Returns a new Iterator object that contains the values for each element in the


Map

object in insertion order.


Map.prototype[@@iterator]()

Returns a new Iterator object that contains a two-member array of


[key, value]

for each element in the

Map

object in insertion order.

Introduction to JavaScript Map object

Before ES6, we often used an object to emulate a map by mapping a key to a value of any type. But using an object as a map has some side effects:

  1. An object always has a default key like the prototype.
  2. A key of an object must be a string or a symbol, you cannot use an object as a key.
  3. An object does not have a property that represents the size of the map.

ES6 provides a new collection type called

Map

that addresses these deficiencies.

By definition, a

Map

object holds key-value pairs. Keys are unique in a Map’s collection. In other words, a key in a Map object only appears once.

Keys and values of a Map can be any values.

When iterating a

Map

object, each iteration returns a 2-member array of

[key, value]

. The iteration order follows the insertion order which corresponds to the order in which each key-value pair was first inserted into the Map by the

set()

method.

To create a new

Map

, you use the following syntax:


let map = new Map([iterable]);

Code language: JavaScript (javascript)

The

Map()

accepts an optional iterable object whose elements are key-value pairs.

JavaScript Map and Set Explained
JavaScript Map and Set Explained

Syntax


Object.entries(obj)

Parameters


obj

An object.

Return value

An array of the given object’s own enumerable string-keyed property key-value pairs. Each key-value pair is an array with two elements: the first element is the property key (which is always a string), and the second element is the property value.

Description


Map

objects are collections of key-value pairs. A key in the

Map

may only occur once; it is unique in the

Map

‘s collection. A

Map

object is iterated by key-value pairs — a

for...of

loop returns a 2-member array of

[key, value]

for each iteration. Iteration happens in insertion order, which corresponds to the order in which each key-value pair was first inserted into the map by the

set()

method (that is, there wasn’t a key with the same value already in the map when

set()

was called).

The specification requires maps to be implemented “that, on average, provide access times that are sublinear on the number of elements in the collection”. Therefore, it could be represented internally as a hash table (with O(1) lookup), a search tree (with O(log(N)) lookup), or any other data structure, as long as the complexity is better than O(N).

Key equality

Value equality is based on the SameValueZero algorithm. (It used to use SameValue, which treated and

-0

as different. Check browser compatibility.) This means

NaN

is considered the same as

NaN

(even though

NaN !== NaN

) and all other values are considered equal according to the semantics of the

===

operator.

ObjectsMaps


Object

is similar to

Map

—both let you set keys to
values, retrieve those values, delete keys, and detect whether something is
stored at a key. For this reason (and because there were no built-in
alternatives),

Object

has been used as

Map

historically.

However, there are important differences that make

Map

preferable in some
cases:

Map Object
Accidental Keys

An

Note: This can be bypassed by using

Security

Setting user-provided key-value pairs on an

Key Types The keys of an
Key Order

The keys in

Although the keys of an ordinary

The order was first defined for own properties only in ECMAScript
2015; ECMAScript 2020 defines order for inherited properties as well.
But note that no single mechanism
iterates
all of an object’s properties; the various mechanisms
each include different subsets of properties.
(

Size

The number of items in a Determining the number of items in an
Iteration

Note:

Performance

Performs better in scenarios involving frequent additions and removals of key-value pairs.

Not optimized for frequent additions and removals of key-value pairs.

Serialization and parsing

No native support for serialization or parsing.

(But you can build your own serialization and parsing support for

Native support for serialization from

Native support for parsing from JSON to

Setting object properties

Setting Object properties works for Map objects as well, and can cause considerable confusion.

Therefore, this appears to work in a way:


const wrongMap = new Map(); wrongMap["bla"] = "blaa"; wrongMap["bla2"] = "blaaa2"; console.log(wrongMap); // Map { bla: 'blaa', bla2: 'blaaa2' }

But that way of setting a property does not interact with the Map data structure. It uses the feature of the generic object. The value of ‘bla’ is not stored in the Map for queries. Other operations on the data fail:


wrongMap.has("bla"); // false wrongMap.delete("bla"); // false console.log(wrongMap); // Map { bla: 'blaa', bla2: 'blaaa2' }

The correct usage for storing data in the Map is through the

set(key, value)

method.


const contacts = new Map(); contacts.set("Jessie", { phone: "213-555-1234", address: "123 N 1st Ave" }); contacts.has("Jessie"); // true contacts.get("Hilary"); // undefined contacts.set("Hilary", { phone: "617-555-4321", address: "321 S 2nd St" }); contacts.get("Jessie"); // {phone: "213-555-1234", address: "123 N 1st Ave"} contacts.delete("Raymond"); // false contacts.delete("Jessie"); // true console.log(contacts.size); // 1

Map-like browser APIs

Browser

Map

-like objects (or “maplike objects”) are Web API interfaces that behave in many ways like a

Map

.

Just like

Map

, entries can be iterated in the same order that they were added to the object.

Map

-like objects and

Map

also have properties and methods that share the same name and behavior.
However unlike

Map

they only allow specific predefined types for the keys and values of each entry.

The allowed types are set in the specification IDL definition.
For example,

RTCStatsReport

is a

Map

-like object that must use strings for keys and objects for values.
This is defined in the specification IDL below:


interface RTCStatsReport { readonly maplike

; };


Map

-like objects are either read-only or read-writable (see the

readonly

keyword in the IDL above).

  • Read-only

    Map

    -like objects have the property

    size

    , and the methods:

    entries()

    ,

    forEach()

    ,

    get()

    ,

    has()

    ,

    keys()

    ,

    values()

    , and

    @@iterator

    .
  • Writeable

    Map

    -like objects additionally have the methods:

    clear()

    ,

    delete()

    , and

    set()

    .

The methods and properties have the same behavior as the equivalent entities in

Map

, except for the restriction on the types of the keys and values.

The following are examples of read-only

Map

-like browser objects:

Creating Maps from arrays and objects | Data Structure | JavaScript
Creating Maps from arrays and objects | Data Structure | JavaScript

Instance properties

These properties are defined on

Map.prototype

and shared by all

Map

instances.


Map.prototype.constructor

The constructor function that created the instance object. For


Map

instances, the initial value is the

Map

constructor.


Map.prototype.size

Returns the number of key/value pairs in the


Map

object.


Map.prototype[@@toStringTag]

The initial value of the


@@toStringTag

property is the string

"Map"

. This property is used in

Object.prototype.toString()

.

Examples

Using Object.entries()


const obj = { foo: "bar", baz: 42 }; console.log(Object.entries(obj)); // [ ['foo', 'bar'], ['baz', 42] ] const arrayLike = { 0: "a", 1: "b", 2: "c" }; console.log(Object.entries(arrayLike)); // [ ['0', 'a'], ['1', 'b'], ['2', 'c'] ] const randomKeyOrder = { 100: "a", 2: "b", 7: "c" }; console.log(Object.entries(randomKeyOrder)); // [ ['2', 'b'], ['7', 'c'], ['100', 'a'] ] // getFoo is a non-enumerable property const myObj = Object.create( {}, { getFoo: { value() { return this.foo; }, }, }, ); myObj.foo = "bar"; console.log(Object.entries(myObj)); // [ ['foo', 'bar'] ]

Using Object.entries() on primitives

Non-object arguments are coerced to objects.

undefined

and

null

cannot be coerced to objects and throw a

TypeError

upfront. Only strings may have own enumerable properties, while all other primitives return an empty array.


// Strings have indices as enumerable own properties console.log(Object.entries("foo")); // [ ['0', 'f'], ['1', 'o'], ['2', 'o'] ] // Other primitives except undefined and null have no own properties console.log(Object.entries(100)); // []

Converting an Object to a Map

Iterating through an Object

Using array destructuring, you can iterate through objects easily.


// Using for...of loop const obj = { a: 5, b: 7, c: 9 }; for (const [key, value] of Object.entries(obj)) { console.log(`${key} ${value}`); // "a 5", "b 7", "c 9" } // Using array methods Object.entries(obj).forEach(([key, value]) => { console.log(`${key} ${value}`); // "a 5", "b 7", "c 9" });

Learn JavaScript OBJECTS in 7 minutes! 🧍
Learn JavaScript OBJECTS in 7 minutes! 🧍

Final thoughts

Although Map perform better, it all comes down to the type of data being used and the operation that needs to be performed. Use Map and Object wisely in the appropriate situations.

I hope you now have a good understanding of using Map and Object in JavaScript.

Thank you for reading!

Syncfusion Essential JS 2 is the only suite you will ever need to build an app. It contains over 65 high-performance, lightweight, modular, and responsive UI components in a single package. Download a free trial to evaluate the controls today.

If you have any questions or comments, you can also contact us through our support forums, support portal, or feedback portal. We are always happy to assist you!

Map

The

Map

object holds key-value pairs and remembers the original insertion order of the keys.
Any value (both objects and primitive values) may be used as either a key or a value.

Description

The

map()

method is an iterative method. It calls a provided

callbackFn

function once for each element in an array and constructs a new array from the results. Read the iterative methods section for more information about how these methods work in general.


callbackFn

is invoked only for array indexes which have assigned values. It is not invoked for empty slots in sparse arrays.

The

map()

method is generic. It only expects the

this

value to have a

length

property and integer-keyed properties.

Since

map

builds a new array, calling it without using the returned array is an anti-pattern; use

forEach

or

for...of

instead.

JavaScript map() method in 7 minutes! 🗺
JavaScript map() method in 7 minutes! 🗺

When to use Map and Object

Map have higher performance and require less code to write, giving them an advantage over Object.

The following are some cases where you can use Map:

  • If you want to use complex data types as keys.
  • If preserving the insertion order of your keys is required.
  • When performing hashing.

However, some cases necessitate the use of an Object. The following are some of them:

  • Object is ideal for cases where we need a simple structure to hold data and the keys are either strings or symbols.
  • Object is unquestionably the best option in scenarios where different logic must be applied to each property piece.
  • When dealing with JSON data, Object have direct support in JSON, but Map do not.

JavaScript Objects vs Maps

Differences between JavaScript Objects and Maps:
Object Map
Not directly iterable Directly iterable
Do not have a size property Have a size property
Keys must be Strings (or Symbols) Keys can be any datatype
Keys are not well ordered Keys are ordered by insertion
Have default keys Do not have default keys
STOP Using Classes In JavaScript | Prime Reacts
STOP Using Classes In JavaScript | Prime Reacts

Browser compatibility

BCD tables only load in the browser

Map and Object are used in JavaScript to store data as dynamic collections of key-value pairs. Since Map is inherited from Object, there are some similarities between the two entities, and prototype functions of Object can be utilized in Map.

However, there are some unique characteristics to each of these entities. This article will examine the differences between Map and Object, their usage, and the best situations where each can be used.

Description


Object.entries()

returns an array whose elements are arrays corresponding to the enumerable string-keyed property key-value pairs found directly upon

object

. This is the same as iterating with a

for...in

loop, except that a

for...in

loop enumerates properties in the prototype chain as well. The order of the array returned by

Object.entries()

is the same as that provided by a

for...in

loop.

If you only need the property keys, use

Object.keys()

instead. If you only need the property values, use

Object.values()

instead.

Map data structure & ES6 map object - Beau teaches JavaScript
Map data structure & ES6 map object – Beau teaches JavaScript

Examples

Mapping an array of numbers to an array of square roots

The following code takes an array of numbers and creates a new array containing the square roots of the numbers in the first array.


const numbers = [1, 4, 9]; const roots = numbers.map((num) => Math.sqrt(num)); // roots is now [1, 2, 3] // numbers is still [1, 4, 9]

Using map to reformat objects in an array

The following code takes an array of objects and creates a new array containing the newly reformatted objects.


const kvArray = [ { key: 1, value: 10 }, { key: 2, value: 20 }, { key: 3, value: 30 }, ]; const reformattedArray = kvArray.map(({ key, value }) => ({ [key]: value })); console.log(reformattedArray); // [{ 1: 10 }, { 2: 20 }, { 3: 30 }] console.log(kvArray); // [ // { key: 1, value: 10 }, // { key: 2, value: 20 }, // { key: 3, value: 30 } // ]

Using parseInt() with map()

It is common to use the callback with one argument (the element being traversed). Certain functions are also commonly used with one argument, even though they take additional optional arguments. These habits may lead to confusing behaviors. Consider:


["1", "2", "3"].map(parseInt);

While one might expect

[1, 2, 3]

, the actual result is

[1, NaN, NaN]

.


parseInt

is often used with one argument, but takes two. The first is an expression and the second is the radix to the callback function,

Array.prototype.map

passes 3 arguments: the element, the index, and the array. The third argument is ignored by

parseInt

— but not the second one! This is the source of possible confusion.

Here is a concise example of the iteration steps:


/* first iteration (index is 0): */ parseInt("1", 0); // 1 /* second iteration (index is 1): */ parseInt("2", 1); // NaN /* third iteration (index is 2): */ parseInt("3", 2); // NaN

To solve this, define another function that only takes one argument:


["1", "2", "3"].map((str) => parseInt(str, 10)); // [1, 2, 3]

You can also use the

Number

function, which only takes one argument:


["1", "2", "3"].map(Number); // [1, 2, 3] // But unlike parseInt(), Number() will also return a float or (resolved) exponential notation: ["1.1", "2.2e2", "3e300"].map(Number); // [1.1, 220, 3e+300] // For comparison, if we use parseInt() on the array above: ["1.1", "2.2e2", "3e300"].map((str) => parseInt(str, 10)); // [1, 2, 3]

See A JavaScript optional argument hazard by Allen Wirfs-Brock for more discussions.

Mapped array contains undefined

When

undefined

or nothing is returned, the resulting array contains

undefined

. If you want to delete the element instead, chain a

filter()

method, or use the

flatMap()

method and return an empty array to signify deletion.


const numbers = [1, 2, 3, 4]; const filteredNumbers = numbers.map((num, index) => { if (index < 3) { return num; } }); // index goes from 0, so the filterNumbers are 1,2,3 and undefined. // filteredNumbers is [1, 2, 3, undefined] // numbers is still [1, 2, 3, 4]

Side-effectful mapping

The callback can have side effects.


const cart = [5, 15, 25]; let total = 0; const withTax = cart.map((cost) => { total += cost; return cost * 1.2; }); console.log(withTax); // [6, 18, 30] console.log(total); // 45

This is not recommended, because copying methods are best used with pure functions. In this case, we can choose to iterate the array twice.


const cart = [5, 15, 25]; const total = cart.reduce((acc, cost) => acc + cost, 0); const withTax = cart.map((cost) => cost * 1.2);

Sometimes this pattern goes to its extreme and the only useful thing that

map()

does is causing side effects.


const products = [ { name: "sports car" }, { name: "laptop" }, { name: "phone" }, ]; products.map((product) => { product.price = 100; });

As mentioned previously, this is an anti-pattern. If you don’t use the return value of

map()

, use

forEach()

or a

for...of

loop instead.


products.forEach((product) => { product.price = 100; });

Or, if you want to create a new array instead:


const productsWithPrice = products.map((product) => { return { ...product, price: 100 }; });

Using the third argument of callbackFn

The

array

argument is useful if you want to access another element in the array, especially when you don’t have an existing variable that refers to the array. The following example first uses

filter()

to extract the positive values and then uses

map()

to create a new array where each element is the average of its neighbors and itself.


const numbers = [3, -1, 1, 4, 1, 5, 9, 2, 6]; const averaged = numbers .filter((num) => num > 0) .map((num, idx, arr) => { // Without the arr argument, there's no way to easily access the // intermediate array without saving it to a variable. const prev = arr[idx - 1]; const next = arr[idx + 1]; let count = 1; let total = num; if (prev !== undefined) { count++; total += prev; } if (next !== undefined) { count++; total += next; } const average = total / count; // Keep two decimal places return Math.round(average * 100) / 100; }); console.log(averaged); // [2, 2.67, 2, 3.33, 5, 5.33, 5.67, 4]

The

array

argument is not the array that is being built — there is no way to access the array being built from the callback function.

Using map() on sparse arrays

A sparse array remains sparse after

map()

. The indices of empty slots are still empty in the returned array, and the callback function won’t be called on them.


console.log( [1, , 3].map((x, index) => { console.log(`Visit ${index}`); return x * 2; }), ); // Visit 0 // Visit 2 // [2, empty, 6]

Calling map() on non-array objects

The

map()

method reads the

length

property of

this

and then accesses each property whose key is a nonnegative integer less than

length

.


const arrayLike = { length: 3, 0: 2, 1: 3, 2: 4, 3: 5, // ignored by map() since length is 3 }; console.log(Array.prototype.map.call(arrayLike, (x) => x ** 2)); // [ 4, 9, 16 ]

This example shows how to iterate through a collection of objects collected by

querySelectorAll

. This is because

querySelectorAll

returns a

NodeList

(which is a collection of objects). In this case, we return all the selected

option

s’ values on the screen:


const elems = document.querySelectorAll("select option:checked"); const values = Array.prototype.map.call(elems, ({ value }) => value);

You can also use

Array.from()

to transform

elems

to an array, and then access the

map()

method.

Manipulation of Map and Object

Construction

Map

A Map can be created using the Map constructor in JavaScript.

const map = new Map([[1, “one”], [2, “two”], [3, “three”]]);

We can set the values initially by parsing an array of arrays. The inner arrays contain a key and a value as their elements. The key field in Map can be of any data type such as number, array, or object.

Object

There are many ways to instantiate an Object.

const obj1 = { 1: “one”, 2: “two”, 3: “three” }; const obj2 = new Object({ 1: “one”, 2: “two”, 3: “three” }); const obj3 = Object.create(obj1);

In the example above, obj1 is created using Object literal syntax while the Object constructor is used for obj2. In obj3, we passed an Object that should be the newly created Object prototype. The data type of the key field in Object is limited to strings and symbols. As a result, the keys given as numbers in the above code snippet will be converted to strings internally.

Item manipulation

Map: Get, set, and delete elements

In Map, we have to use the set() method to insert values, the get() method to access elements, and the delete() method to delete elements.

const map = new Map(); map.set(1, “one”); console.log(map.get(1)); // output: one map.delete(1); console.log(map); // Map(0) {}

The set() method requires two parameters to initialize the key and value of a Map element. On the other hand, the get() method returns the value of the key we pass as the parameter. We can delete an element by passing the key to the delete() method.

Object: Dot notation

We can use either dot notation or square bracket notation to access elements in an Object.

const obj = {}; obj.a = “one” obj[“b”] = “two” console.log(obj.a); // output: one console.log(obj[“b”]); //output: two delete obj.a delete obj[“b”] console.log(obj); // output: {}

Dot notation is straightforward, and we can access elements directly by their key. On the other hand, square bracket notation should be used in full when dynamically accessing the element. Also, we can use the delete keyword to delete elements from an Object.

Read keys and values

Map

In Map, we can use the keys() method to get the list of keys in a map.

const map = new Map([[1, “one”], [2, “two”]]); console.log(map.keys()); // output: [Map Iterator] { 1, 2 } console.log(Array.from(map.keys())); // output: [1, 2] console.log(map.values()); // output: [Map Iterator] { ‘one’, ‘two’ } console.log(Array.from(map.values())); // output: [‘one’, ‘two’] console.log(map.entries()); // output [Map Iterator] { [1, ‘one’], [2, ‘two’] } console.log(Array.from(map.entries())); // output [ [1, ‘one’], [2, ‘two’] ]

map.keys() returns a Map Iterator with the keys, while map.values() returns a Map Iterator with values. On the other hand, map.entries() can be used to return a Map Iterator with key-value pairs. We can convert these Map Iterators to arrays using Array.from().

Object

To get the keys to an Object, we can use Object.keys() and Object.values() to get the values, while Object.entries() can be used to get the key-value pairs.

const obj = { 1: “one”, 2: “two” }; console.log(Object.keys(obj)); // output: [‘1’, ‘2’] console.log(Object.values(obj)); // output: [‘one’, ‘two’] console.log(Object.entries(obj)); // output: [ [‘1’, ‘one’], [‘2’, ‘two’] ]

The above functions return an array of keys, values, or key-value pairs of the Object we pass as the parameter.

Check if a key exists

Map

Map have the has() method to check if a key exists.

console.log(map.has(2)); // output: true or false

Object

The following methods can be used to check the existence of a key in an Object.

console.log(2 in obj); // output: true or false console.log(obj.hasOwnProperty(2)); // output: true or false

Get length

Map

We can get the size or the number of elements of a Map using the size property.

console.log(map.size); // output: 2

Object

We can get the size of an Object as shown below.

console.log(Object.keys(obj).length); // output: 2

Here, we got the keys array from the Object and used length to get the number of elements, similar to the Object’s size.

Iteration

Map

There are several ways to iterate over the elements in a Map. The following code example illustrates iterating using for and forEach loops.

//method 1 for (const [ key, value ] of map) { console.log(value); }; //method 2 map.forEach((value, key) => console.log(value));

Object

Similar to Map, Object can also be iterated in many ways. The following code example illustrates iterating using for and forEach loops.

//method 1 for (const [key, value ] of Object.entries(obj)) { console.log(value); }; //method 2 Object.entries(obj).forEach(([ key, value ]) => console.log(value));

Unlike in Map, we need helper functions to access key-value pairs in Object.

OpenLayers Tutorial 1 | Map with a marker using JavaScript
OpenLayers Tutorial 1 | Map with a marker using JavaScript

Syntax


map(callbackFn) map(callbackFn, thisArg)

Parameters


callbackFn

A function to execute for each element in the array. Its return value is added as a single element in the new array. The function is called with the following arguments:


thisArg

Optional

A value to use as


this

when executing

callbackFn

. See iterative methods.

Return value

A new array with each element being the result of the callback function.

Instance properties

These properties are defined on

Map.prototype

and shared by all

Map

instances.


Map.prototype.constructor

The constructor function that created the instance object. For


Map

instances, the initial value is the

Map

constructor.


Map.prototype.size

Returns the number of key/value pairs in the


Map

object.


Map.prototype[@@toStringTag]

The initial value of the


@@toStringTag

property is the string

"Map"

. This property is used in

Object.prototype.toString()

.

Map Live User Location using Leaflet.js and OpenStreetMap - JavaScript Tutorial
Map Live User Location using Leaflet.js and OpenStreetMap – JavaScript Tutorial

Browser compatibility

BCD tables only load in the browser

You have an object that you want to map over. Suppose you want to map over the following object and double each value:

const myObject = { a: 2, b: 4, c: 6 };

With an array, you can use the

map()

function to call a function on every element of an array to change the values and return a new array, leaving the original array unchanged. JavaScript does not have a map function for objects. How do you create one?

The two solutions described below involve converting an object’s keys or keys and values into an array so that JavaScript array methods can be used to iterate through the values, which allows us to change them. The array is then converted back into an object.

You can create an object map function that takes in the object that you want to map over and a map function. In the example code below, the map function that’s passed into the

objectMap

function as an argument doubles the value of the input:

function mapFn(value) { return value * 2; } function objectMap(obj, fn) { const newObject = {}; Object.keys(obj).forEach((key) => { newObject[key] = fn(obj[key]); }); return newObject; } console.log(objectMap(myObject, mapFn)); // { a: 4, b: 8, c: 12 }

The

objectMap

function first creates an empty object. An array of the keys of the passed-in object is created using the

Object.keys()

method. This array is mapped over using the

forEach()

array method. For each value, which is a key of the

obj

argument, we create a key-value pair for

newObject

. We pass the value into the map function argument,

fn

, to change the values as needed. We then return the

newObject

that’s created.


Object.entries()Method

Alternatively, you can use the

Object.entries()

method to convert the

obj

argument to a nested array where the first element of each nested array is an object key and the second element of each nested array is an object value. You can then use the array

map()

function to change the value of each element using the map function argument. The

Object.fromEntries()

method is then used to convert this array of key-value pairs into an object:

function mapFn(value) { return value * 2; } function objectMap(obj, fn) { return Object.fromEntries( Object.entries(obj).map(([key, value]) => [key, fn(value)]) ); } console.log(objectMap(myObject, mapFn)); // { a: 4, b: 8, c: 12 }

Get actionable, code-level insights to resolve JavaScript performance bottlenecks and errors.

Create a free Sentry account

Create a JavaScript project and note your DSN

Grab the Sentry JavaScript SDK

Sentry.init({ dsn: ‘https://

@sentry.io/ ‘ });

Check our documentation for the latest instructions.

Loved by over 4 million developers and more than 90,000 organizations worldwide, Sentry provides code-level observability to many of the world’s best-known companies like Disney, Peloton, Cloudflare, Eventbrite, Slack, Supercell, and Rockstar Games. Each month we process billions of exceptions from the most popular products on the internet.

Here’s a quick look at how Sentry handles your personal information (PII).

×

We collect PII about people browsing our website, users of the Sentry service, prospective customers, and people who otherwise interact with us.

What if my PII is included in data sent to Sentry by a Sentry customer (e.g., someone using Sentry to monitor their app)? In this case you have to contact the Sentry customer (e.g., the maker of the app). We do not control the data that is sent to us through the Sentry service for the purposes of application monitoring.

Am I included?

We may disclose your PII to the following type of recipients:

You may have the following rights related to your PII:

If you have any questions or concerns about your privacy at Sentry, please email us at [email protected].

If you are a California resident, see our Supplemental notice.

Map and Object are used in JavaScript to store data as dynamic collections of key-value pairs. Since Map is inherited from Object, there are some similarities between the two entities, and prototype functions of Object can be utilized in Map.

However, there are some unique characteristics to each of these entities. This article will examine the differences between Map and Object, their usage, and the best situations where each can be used.

Browser Support

JavaScript Maps are supported in all browsers, except Internet Explorer:

Chrome Edge Firefox Safari Opera

You have an object that you want to map over. Suppose you want to map over the following object and double each value:

const myObject = { a: 2, b: 4, c: 6 };

With an array, you can use the

map()

function to call a function on every element of an array to change the values and return a new array, leaving the original array unchanged. JavaScript does not have a map function for objects. How do you create one?

The two solutions described below involve converting an object’s keys or keys and values into an array so that JavaScript array methods can be used to iterate through the values, which allows us to change them. The array is then converted back into an object.

You can create an object map function that takes in the object that you want to map over and a map function. In the example code below, the map function that’s passed into the

objectMap

function as an argument doubles the value of the input:

function mapFn(value) { return value * 2; } function objectMap(obj, fn) { const newObject = {}; Object.keys(obj).forEach((key) => { newObject[key] = fn(obj[key]); }); return newObject; } console.log(objectMap(myObject, mapFn)); // { a: 4, b: 8, c: 12 }

The

objectMap

function first creates an empty object. An array of the keys of the passed-in object is created using the

Object.keys()

method. This array is mapped over using the

forEach()

array method. For each value, which is a key of the

obj

argument, we create a key-value pair for

newObject

. We pass the value into the map function argument,

fn

, to change the values as needed. We then return the

newObject

that’s created.


Object.entries()Method

Alternatively, you can use the

Object.entries()

method to convert the

obj

argument to a nested array where the first element of each nested array is an object key and the second element of each nested array is an object value. You can then use the array

map()

function to change the value of each element using the map function argument. The

Object.fromEntries()

method is then used to convert this array of key-value pairs into an object:

function mapFn(value) { return value * 2; } function objectMap(obj, fn) { return Object.fromEntries( Object.entries(obj).map(([key, value]) => [key, fn(value)]) ); } console.log(objectMap(myObject, mapFn)); // { a: 4, b: 8, c: 12 }

Get actionable, code-level insights to resolve JavaScript performance bottlenecks and errors.

Create a free Sentry account

Create a JavaScript project and note your DSN

Grab the Sentry JavaScript SDK

Sentry.init({ dsn: ‘https://

@sentry.io/ ‘ });

Check our documentation for the latest instructions.

Loved by over 4 million developers and more than 90,000 organizations worldwide, Sentry provides code-level observability to many of the world’s best-known companies like Disney, Peloton, Cloudflare, Eventbrite, Slack, Supercell, and Rockstar Games. Each month we process billions of exceptions from the most popular products on the internet.

Here’s a quick look at how Sentry handles your personal information (PII).

×

We collect PII about people browsing our website, users of the Sentry service, prospective customers, and people who otherwise interact with us.

What if my PII is included in data sent to Sentry by a Sentry customer (e.g., someone using Sentry to monitor their app)? In this case you have to contact the Sentry customer (e.g., the maker of the app). We do not control the data that is sent to us through the Sentry service for the purposes of application monitoring.

Am I included?

We may disclose your PII to the following type of recipients:

You may have the following rights related to your PII:

If you have any questions or concerns about your privacy at Sentry, please email us at [email protected].

If you are a California resident, see our Supplemental notice.

Array.prototype.map()

The

map()

method of

Array

instances creates
a new array populated with the results of calling a provided function on
every element in the calling array.

Hash Tables - Beau teaches JavaScript
Hash Tables – Beau teaches JavaScript

Examples

Using the Map object


const myMap = new Map(); const keyString = "a string"; const keyObj = {}; const keyFunc = function () {}; // setting the values myMap.set(keyString, "value associated with 'a string'"); myMap.set(keyObj, "value associated with keyObj"); myMap.set(keyFunc, "value associated with keyFunc"); console.log(myMap.size); // 3 // getting the values console.log(myMap.get(keyString)); // "value associated with 'a string'" console.log(myMap.get(keyObj)); // "value associated with keyObj" console.log(myMap.get(keyFunc)); // "value associated with keyFunc" console.log(myMap.get("a string")); // "value associated with 'a string'", because keyString === 'a string' console.log(myMap.get({})); // undefined, because keyObj !== {} console.log(myMap.get(function () {})); // undefined, because keyFunc !== function () {}

Using NaN as Map keys


NaN

can also be used as a key. Even though every

NaN

is
not equal to itself (

NaN !== NaN

is true), the following example works because

NaN

s are indistinguishable from each other:


const myMap = new Map(); myMap.set(NaN, "not a number"); myMap.get(NaN); // "not a number" const otherNaN = Number("foo"); myMap.get(otherNaN); // "not a number"

Iterating Map with for…of

Maps can be iterated using a

for...of

loop:


const myMap = new Map(); myMap.set(0, "zero"); myMap.set(1, "one"); for (const [key, value] of myMap) { console.log(`${key} = ${value}`); } // 0 = zero // 1 = one for (const key of myMap.keys()) { console.log(key); } // 0 // 1 for (const value of myMap.values()) { console.log(value); } // zero // one for (const [key, value] of myMap.entries()) { console.log(`${key} = ${value}`); } // 0 = zero // 1 = one

Iterating Map with forEach()

Maps can be iterated using the

forEach()

method:


myMap.forEach((value, key) => { console.log(`${key} = ${value}`); }); // 0 = zero // 1 = one

Relation with Array objects


const kvArray = [ ["key1", "value1"], ["key2", "value2"], ]; // Use the regular Map constructor to transform a 2D key-value Array into a map const myMap = new Map(kvArray); console.log(myMap.get("key1")); // "value1" // Use Array.from() to transform a map into a 2D key-value Array console.log(Array.from(myMap)); // Will show you exactly the same Array as kvArray // A succinct way to do the same, using the spread syntax console.log([...myMap]); // Or use the keys() or values() iterators, and convert them to an array console.log(Array.from(myMap.keys())); // ["key1", "key2"]

Cloning and merging Maps

Just like

Array

s,

Map

s can be cloned:


const original = new Map([[1, "one"]]); const clone = new Map(original); console.log(clone.get(1)); // one console.log(original === clone); // false (useful for shallow comparison)

Note: Keep in mind that the data itself is not cloned.

Maps can be merged, maintaining key uniqueness:


const first = new Map([ [1, "one"], [2, "two"], [3, "three"], ]); const second = new Map([ [1, "uno"], [2, "dos"], ]); // Merge two maps. The last repeated key wins. // Spread syntax essentially converts a Map to an Array const merged = new Map([...first, ...second]); console.log(merged.get(1)); // uno console.log(merged.get(2)); // dos console.log(merged.get(3)); // three

Maps can be merged with Arrays, too:


const first = new Map([ [1, "one"], [2, "two"], [3, "three"], ]); const second = new Map([ [1, "uno"], [2, "dos"], ]); // Merge maps with an array. The last repeated key wins. const merged = new Map([...first, ...second, [1, "eins"]]); console.log(merged.get(1)); // eins console.log(merged.get(2)); // dos console.log(merged.get(3)); // three

Browser compatibility

BCD tables only load in the browser

How about a one-liner in JS ES10 / ES2019 ?

Making use of

Object.entries()

and

Object.fromEntries()

:


let newObj = Object.fromEntries(Object.entries(obj).map(([k, v]) => [k, v * v]));

The same thing written as a function:


function objMap(obj, func) {
return Object.fromEntries(Object.entries(obj).map(([k, v]) => [k, func(v)]));
}
// To square each value you can call it like this:
let mappedObj = objMap(obj, (x) => x * x);

This function uses recursion to square nested objects as well:


function objMap(obj, func) {
return Object.fromEntries(
Object.entries(obj).map(([k, v]) =>
[k, v === Object(v) ? objMap(v, func) : func(v)]
)
);
}
// To square each value you can call it like this:
let mappedObj = objMap(obj, (x) => x * x);

With ES7 / ES2016 you can’t use

Objects.fromEntries

, but you can achieve the same using

Object.assign

in combination with spread operators and computed key names syntax:


let newObj = Object.assign({}, ...Object.entries(obj).map(([k, v]) => ({[k]: v * v})));

ES6 / ES2015 Doesn’t allow

Object.entries

, but you could use

Object.keys

instead:


let newObj = Object.assign({}, ...Object.keys(obj).map(k => ({[k]: obj[k] * obj[k]})));

ES6 also introduced

for...of

loops, which allow a more imperative style:


let newObj = {}
for (let [k, v] of Object.entries(obj)) {
newObj[k] = v * v;
}

array.reduce()

Instead of

Object.fromEntries

and

Object.assign

you can also use reduce for this:


let newObj = Object.entries(obj).reduce((p, [k, v]) => ({ ...p, [k]: v * v }), {});

Inherited properties and the prototype chain:

In some rare situation you may need to map a class-like object which holds properties of an inherited object on its prototype-chain. In such cases

Object.keys()

and

Object.entries()

won’t work, because these functions do not include the prototype chain.

If you need to map inherited properties, you can use

for (key in myObj) {...}

.

Here is an example of such situation:


const obj1 = { 'a': 1, 'b': 2, 'c': 3}
const obj2 = Object.create(obj1); // One of multiple ways to inherit an object in JS.
// Here you see how the properties of obj1 sit on the 'prototype' of obj2
console.log(obj2) // Prints: obj2.__proto__ = { 'a': 1, 'b': 2, 'c': 3}
console.log(Object.keys(obj2)); // Prints: an empty Array.
console.log(Object.entries(obj2)); // Prints: an empty Array.
for (let key in obj2) {
console.log(key); // Prints: 'a', 'b', 'c'
}

However, please do me a favor and avoid inheritance. 🙂

JavaScript Maps

A Map holds key-value pairs where the keys can be any datatype.

A Map remembers the original insertion order of the keys.

A Map has a property that represents the size of the map.

Map through State Array (Loop) - React tutorial 8
Map through State Array (Loop) – React tutorial 8

Description


Map

objects are collections of key-value pairs. A key in the

Map

may only occur once; it is unique in the

Map

‘s collection. A

Map

object is iterated by key-value pairs — a

for...of

loop returns a 2-member array of

[key, value]

for each iteration. Iteration happens in insertion order, which corresponds to the order in which each key-value pair was first inserted into the map by the

set()

method (that is, there wasn’t a key with the same value already in the map when

set()

was called).

The specification requires maps to be implemented “that, on average, provide access times that are sublinear on the number of elements in the collection”. Therefore, it could be represented internally as a hash table (with O(1) lookup), a search tree (with O(log(N)) lookup), or any other data structure, as long as the complexity is better than O(N).

Key equality

Value equality is based on the SameValueZero algorithm. (It used to use SameValue, which treated and

-0

as different. Check browser compatibility.) This means

NaN

is considered the same as

NaN

(even though

NaN !== NaN

) and all other values are considered equal according to the semantics of the

===

operator.

ObjectsMaps


Object

is similar to

Map

—both let you set keys to
values, retrieve those values, delete keys, and detect whether something is
stored at a key. For this reason (and because there were no built-in
alternatives),

Object

has been used as

Map

historically.

However, there are important differences that make

Map

preferable in some
cases:

Map Object
Accidental Keys

An

Note: This can be bypassed by using

Security

Setting user-provided key-value pairs on an

Key Types The keys of an
Key Order

The keys in

Although the keys of an ordinary

The order was first defined for own properties only in ECMAScript
2015; ECMAScript 2020 defines order for inherited properties as well.
But note that no single mechanism
iterates
all of an object’s properties; the various mechanisms
each include different subsets of properties.
(

Size

The number of items in a Determining the number of items in an
Iteration

Note:

Performance

Performs better in scenarios involving frequent additions and removals of key-value pairs.

Not optimized for frequent additions and removals of key-value pairs.

Serialization and parsing

No native support for serialization or parsing.

(But you can build your own serialization and parsing support for

Native support for serialization from

Native support for parsing from JSON to

Setting object properties

Setting Object properties works for Map objects as well, and can cause considerable confusion.

Therefore, this appears to work in a way:


const wrongMap = new Map(); wrongMap["bla"] = "blaa"; wrongMap["bla2"] = "blaaa2"; console.log(wrongMap); // Map { bla: 'blaa', bla2: 'blaaa2' }

But that way of setting a property does not interact with the Map data structure. It uses the feature of the generic object. The value of ‘bla’ is not stored in the Map for queries. Other operations on the data fail:


wrongMap.has("bla"); // false wrongMap.delete("bla"); // false console.log(wrongMap); // Map { bla: 'blaa', bla2: 'blaaa2' }

The correct usage for storing data in the Map is through the

set(key, value)

method.


const contacts = new Map(); contacts.set("Jessie", { phone: "213-555-1234", address: "123 N 1st Ave" }); contacts.has("Jessie"); // true contacts.get("Hilary"); // undefined contacts.set("Hilary", { phone: "617-555-4321", address: "321 S 2nd St" }); contacts.get("Jessie"); // {phone: "213-555-1234", address: "123 N 1st Ave"} contacts.delete("Raymond"); // false contacts.delete("Jessie"); // true console.log(contacts.size); // 1

Map-like browser APIs

Browser

Map

-like objects (or “maplike objects”) are Web API interfaces that behave in many ways like a

Map

.

Just like

Map

, entries can be iterated in the same order that they were added to the object.

Map

-like objects and

Map

also have properties and methods that share the same name and behavior.
However unlike

Map

they only allow specific predefined types for the keys and values of each entry.

The allowed types are set in the specification IDL definition.
For example,

RTCStatsReport

is a

Map

-like object that must use strings for keys and objects for values.
This is defined in the specification IDL below:


interface RTCStatsReport { readonly maplike

; };


Map

-like objects are either read-only or read-writable (see the

readonly

keyword in the IDL above).

  • Read-only

    Map

    -like objects have the property

    size

    , and the methods:

    entries()

    ,

    forEach()

    ,

    get()

    ,

    has()

    ,

    keys()

    ,

    values()

    , and

    @@iterator

    .
  • Writeable

    Map

    -like objects additionally have the methods:

    clear()

    ,

    delete()

    , and

    set()

    .

The methods and properties have the same behavior as the equivalent entities in

Map

, except for the restriction on the types of the keys and values.

The following are examples of read-only

Map

-like browser objects:

Objects as Keys

Being able to use objects as keys is an important Map feature.

Example

const apples = {name: ‘Apples’};

const bananas = {name: ‘Bananas’};

const oranges = {name: ‘Oranges’};

// Create a Map

const fruits = new Map();

// Add new Elements to the Map

fruits.set(apples, 500);

fruits.set(bananas, 300);

fruits.set(oranges, 200);

Remember: The key is an object (apples), not a string (“apples”):

Example

Objects: Nested Arrays & Objects--The Modern JavaScript Bootcamp
Objects: Nested Arrays & Objects–The Modern JavaScript Bootcamp

JavaScript Map examples

Let’s take some examples of using a Map object.

Create a new Map object

Suppose you have a list of

user

objects as follows:


let john = {name: 'John Doe'}, lily = {name: 'Lily Bush'}, peter = {name: 'Peter Drucker'};

Code language: JavaScript (javascript)

Assuming that you have to create a map of users and roles. In this case, you use the following code:


let userRoles = new Map();

Code language: JavaScript (javascript)

The

userRoles

is an instance of the

Map

object and its type is an object as illustrated in the following example:


console.log(typeof(userRoles)); // object console.log(userRoles instanceof Map); // true

Code language: JavaScript (javascript)

Add elements to a Map

To assign a role to a user, you use the

set()

method:


userRoles.set(john, 'admin');

Code language: JavaScript (javascript)

The

set()

method maps user

john

with the

admin

role. Since the

set()

method is chainable, you can save some typing as shown in this example:


userRoles.set(lily, 'editor') .set(peter, 'subscriber');

Code language: JavaScript (javascript)

Initialize a map with an iterable object

As mentioned earlier, you can pass an iterable object to the

Map()

constructor:


let userRoles = new Map([ [john, 'admin'], [lily, 'editor'], [peter, 'subscriber'] ]);

Code language: JavaScript (javascript)

Get an element from a map by key

If you want to see the roles of

John

, you use the

get()

method:


userRoles.get(john); // admin

Code language: JavaScript (javascript)

If you pass a key that does not exist, the

get()

method will return

undefined

.


let foo = {name: 'Foo'}; userRoles.get(foo); //undefined

Code language: JavaScript (javascript)

Check the existence of an element by key

To check if a key exists in the map, you use the

has()

method.


userRoles.has(foo); // false userRoles.has(lily); // true

Code language: JavaScript (javascript)

Get the number of elements in the map

The

size

property returns the number of entries of the Map object.


console.log(userRoles.size); // 3

Code language: JavaScript (javascript)

Iterate over map keys

To get the keys of a

Map

object, you use the

keys()

method. The

keys()

returns a new iterator object that contains the keys of elements in the map.

The following example displays the username of the users in the

userRoles

map object.


let john = { name: 'John Doe' }, lily = { name: 'Lily Bush' }, peter = { name: 'Peter Drucker' }; let userRoles = new Map([ [john, 'admin'], [lily, 'editor'], [peter, 'subscriber'], ]); for (const user of userRoles.keys()) { console.log(user.name); }

Code language: JavaScript (javascript)

Output:


John Doe Lily Bush Peter Drucker

Iterate over map values

Similarly, you can use the

values()

method to get an iterator object that contains values for all the elements in the map:


let john = { name: 'John Doe' }, lily = { name: 'Lily Bush' }, peter = { name: 'Peter Drucker' }; let userRoles = new Map([ [john, 'admin'], [lily, 'editor'], [peter, 'subscriber'], ]); for (let role of userRoles.values()) { console.log(role); }

Code language: JavaScript (javascript)

Output:


admin editor subscriber

Iterate over map elements

Also, the

entries()

method returns an iterator object that contains an array of

[key,value]

of each element in the

Map

object:


let john = { name: 'John Doe' }, lily = { name: 'Lily Bush' }, peter = { name: 'Peter Drucker' }; let userRoles = new Map([ [john, 'admin'], [lily, 'editor'], [peter, 'subscriber'], ]); for (const role of userRoles.entries()) { console.log(`${role[0].name}: ${role[1]}`); }

Code language: JavaScript (javascript)

To make the iteration more natural, you can use destructuring as follows:


let john = { name: 'John Doe' }, lily = { name: 'Lily Bush' }, peter = { name: 'Peter Drucker' }; let userRoles = new Map([ [john, 'admin'], [lily, 'editor'], [peter, 'subscriber'], ]); for (let [user, role] of userRoles.entries()) { console.log(`${user.name}: ${role}`); }

Code language: JavaScript (javascript)

In addition to

for...of

loop, you can use the

forEach()

method of the map object:


let john = { name: 'John Doe' }, lily = { name: 'Lily Bush' }, peter = { name: 'Peter Drucker' }; let userRoles = new Map([ [john, 'admin'], [lily, 'editor'], [peter, 'subscriber'], ]); userRoles.forEach((role, user) => console.log(`${user.name}: ${role}`));

Code language: JavaScript (javascript)

Convert map keys or values to an array

Sometimes, you want to work with an array instead of an iterable object, in this case, you can use the spread operator.

The following example converts keys for each element into an array of keys:


var keys = [...userRoles.keys()]; console.log(keys);

Code language: JavaScript (javascript)

Output:


[ { name: 'John Doe' }, { name: 'Lily Bush' }, { name: 'Peter Drucker' } ]

Code language: JavaScript (javascript)

The following converts the values of elements to an array:


let roles = [...userRoles.values()]; console.log(roles);

Code language: JavaScript (javascript)

Output


[ 'admin', 'editor', 'subscriber' ]

Code language: JSON / JSON with Comments (json)

Delete an element by key

To delete an entry in the map, you use the

delete()

method.


userRoles.delete(john);

Code language: CSS (css)

Delete all elements in the map

To delete all entries in the

Map

object, you use the

clear()

method:


userRoles.clear();

Code language: CSS (css)

Hence, the size of the map now is zero.


console.log(userRoles.size); // 0

Code language: JavaScript (javascript)

WeakMap

A

WeakMap

is similar to a

Map

except for the keys of a

WeakMap

must be objects. It means that when a reference to a key (an object) is out of scope, the corresponding value is automatically released from the memory.

A

WeakMap

only has subset methods of a

Map

object:


  • get(key)

  • set(key, value)

  • has(key)

  • delete(key)

Here are the main differences between a

Map

and a

WeekMap

:

  • Elements of a WeakMap cannot be iterated.
  • Cannot clear all elements at once.
  • Cannot check the size of a WeakMap.

In this tutorial, you have learned how to work with the JavaScript Map object and its useful methods to manipulate entries in the map.

Array Iteration: 8 Methods - map, filter, reduce, some, every, find, findIndex, forEach
Array Iteration: 8 Methods – map, filter, reduce, some, every, find, findIndex, forEach

Syntax


get(key)

Parameters


key

The key of the element to return from the


Map

object.

Return value

The element associated with the specified key, or

undefined

if the key can’t be found in the

Map

object.

Final thoughts

Although Map perform better, it all comes down to the type of data being used and the operation that needs to be performed. Use Map and Object wisely in the appropriate situations.

I hope you now have a good understanding of using Map and Object in JavaScript.

Thank you for reading!

Syncfusion Essential JS 2 is the only suite you will ever need to build an app. It contains over 65 high-performance, lightweight, modular, and responsive UI components in a single package. Download a free trial to evaluate the controls today.

If you have any questions or comments, you can also contact us through our support forums, support portal, or feedback portal. We are always happy to assist you!

Map.prototype.get()

The

get()

method of

Map

instances returns a specified element from this map. If the
value that is associated to the provided key is an object, then you will get a
reference to that object and any change made to that object will effectively
modify it inside the

Map

object.

JavaScript Array Map
JavaScript Array Map

Map Methods

Method Description
new Map() Creates a new Map object
set() Sets the value for a key in a Map
get() Gets the value for a key in a Map
clear() Removes all the elements from a Map
delete() Removes a Map element specified by a key
has() Returns true if a key exists in a Map
forEach() Invokes a callback for each key/value pair in a Map
entries() Returns an iterator object with the [key, value] pairs in a Map
keys() Returns an iterator object with the keys in a Map
values() Returns an iterator object of the values in a Map
Property Description
size Returns the number of Map elements

Instance methods


Map.prototype.clear()

Removes all key-value pairs from the


Map

object.


Map.prototype.delete()

Returns


true

if an element in the

Map

object existed and has been removed, or

false

if the element does not exist.

map.has(key)

will return

false

afterwards.


Map.prototype.entries()

Returns a new Iterator object that contains a two-member array of


[key, value]

for each element in the

Map

object in insertion order.


Map.prototype.forEach()

Calls


callbackFn

once for each key-value pair present in the

Map

object, in insertion order. If a

thisArg

parameter is provided to

forEach

, it will be used as the

this

value for each callback.


Map.prototype.get()

Returns the value associated to the passed key, or


undefined

if there is none.


Map.prototype.has()

Returns a boolean indicating whether a value has been associated with the passed key in the


Map

object or not.


Map.prototype.keys()

Returns a new Iterator object that contains the keys for each element in the


Map

object in insertion order.


Map.prototype.set()

Sets the value for the passed key in the


Map

object. Returns the

Map

object.


Map.prototype.values()

Returns a new Iterator object that contains the values for each element in the


Map

object in insertion order.


Map.prototype[@@iterator]()

Returns a new Iterator object that contains a two-member array of


[key, value]

for each element in the

Map

object in insertion order.

If Dev and Ops had a Baby, it would be Called Winglang - Elad Ben Israel
If Dev and Ops had a Baby, it would be Called Winglang – Elad Ben Israel

Keywords searched by users: js map on object

5 Reasons To Choose Javascript Maps Over Objects For Storing Key-Value  Pairs(With Examples) - Dev Community
5 Reasons To Choose Javascript Maps Over Objects For Storing Key-Value Pairs(With Examples) – Dev Community
Use This Trick To Map Over Single Objects In Javascript - Dev Community
Use This Trick To Map Over Single Objects In Javascript – Dev Community
Javascript Map Object | Examples Of Javascript Map Object
Javascript Map Object | Examples Of Javascript Map Object
Map Vs Object En Javascript. ¿Qué Son Los Map Y Cuándo Usarlos? 🤔 - Youtube
Map Vs Object En Javascript. ¿Qué Son Los Map Y Cuándo Usarlos? 🤔 – Youtube
What Is The Difference Between Javascript Map And Object? - Youtube
What Is The Difference Between Javascript Map And Object? – Youtube
Map And Set In Javascript - Scaler Topics
Map And Set In Javascript – Scaler Topics
Builder.Io On X:
Builder.Io On X: “When To Use Map Vs. Object, A Reference Guide. Https://T.Co/F0Gz3Vmjxp” / X
When You Should Prefer Map Over Object In Javascript
When You Should Prefer Map Over Object In Javascript
When You Should Prefer Map Over Object In Javascript
When You Should Prefer Map Over Object In Javascript
Simplifying Maps In The Javascript – Dhananjay Kumar
Simplifying Maps In The Javascript – Dhananjay Kumar
When You Should Prefer Map Over Object In Javascript
When You Should Prefer Map Over Object In Javascript
Javascript Map Object | Examples Of Javascript Map Object
Javascript Map Object | Examples Of Javascript Map Object
Map Vs Object In Javascript - Youtube
Map Vs Object In Javascript – Youtube
Map In Javascript | Learn The Different Map Methods In Javascript
Map In Javascript | Learn The Different Map Methods In Javascript

See more here: kientrucannam.vn

Trả lời

Email của bạn sẽ không được hiển thị công khai. Các trường bắt buộc được đánh dấu *