JavaScript Map vs. Object | Syncfusion Blogs
Live Chat Icon For mobile
Live Chat Icon
Popular Categories.NET  (174).NET Core  (29).NET MAUI  (207)Angular  (109)ASP.NET  (51)ASP.NET Core  (82)ASP.NET MVC  (89)Azure  (41)Black Friday Deal  (1)Blazor  (217)BoldSign  (14)DocIO  (24)Essential JS 2  (107)Essential Studio  (200)File Formats  (66)Flutter  (133)JavaScript  (221)Microsoft  (119)PDF  (81)Python  (1)React  (100)Streamlit  (1)Succinctly series  (131)Syncfusion  (917)TypeScript  (33)Uno Platform  (3)UWP  (4)Vue  (45)Webinar  (51)Windows Forms  (61)WinUI  (68)WPF  (159)Xamarin  (161)XlsIO  (36)Other CategoriesBarcode  (5)BI  (29)Bold BI  (8)Bold Reports  (2)Build conference  (8)Business intelligence  (55)Button  (4)C#  (148)Chart  (131)Cloud  (15)Company  (443)Dashboard  (8)Data Science  (3)Data Validation  (8)DataGrid  (63)Development  (629)Doc  (8)DockingManager  (1)eBook  (99)Enterprise  (22)Entity Framework  (5)Essential Tools  (14)Excel  (40)Extensions  (22)File Manager  (7)Gantt  (18)Gauge  (12)Git  (5)Grid  (31)HTML  (13)Installer  (2)Knockout  (2)Language  (1)LINQPad  (1)Linux  (2)M-Commerce  (1)Metro Studio  (11)Mobile  (507)Mobile MVC  (9)OLAP server  (1)Open source  (1)Orubase  (12)Partners  (21)PDF viewer  (43)Performance  (12)PHP  (2)PivotGrid  (4)Predictive Analytics  (6)Report Server  (3)Reporting  (10)Reporting / Back Office  (11)Rich Text Editor  (12)Road Map  (12)Scheduler  (52)Security  (3)SfDataGrid  (9)Silverlight  (21)Sneak Peek  (31)Solution Services  (4)Spreadsheet  (11)SQL  (10)Stock Chart  (1)Surface  (4)Tablets  (5)Theme  (12)Tips and Tricks  (112)UI  (387)Uncategorized  (68)Unix  (2)User interface  (68)Visual State Manager  (2)Visual Studio  (31)Visual Studio Code  (19)Web  (593)What's new  (332)Windows 8  (19)Windows App  (2)Windows Phone  (15)Windows Phone 7  (9)WinRT  (26)
JS Map vs Object

JavaScript Map vs. Object

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.

What is a Map?

A Map is a data structure that stores data as unique key-value pairs in which the insertion order is retained. It helps to avoid duplicity.

What is an Object?

The concept of an Object is very similar to that of a Map: it stores data using a key-value pair. However, minor variations make Map work better under specific conditions, mainly because Object do not preserve the insertion order of elements when storing the data.

Manipulation of Map and Object

1. 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.

2. 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.

3. 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.

4. 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

5. 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.

6. 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.

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.

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 forumssupport portal, or feedback portal. We are always happy to assist you!

Related blogs

Tags:

Share this post:

Popular Now

Be the first to get updates

Subscribe RSS feed

Be the first to get updates

Subscribe RSS feed