Object vs Map
Storing the key and value pairs is a common thing we have to deal with in JavaScript. The most basic approach is to use an object:
const person = {};
person.name = 'Foo';
person.age = 20;
// Or
const person = {
name: 'Foo',
age: 20,
};
Being introduced from ES6, the Map
data structure provides the same ability. The sample code above can be rewritten with Map
as following:
const person = new Map();
person.set('name', 'Foo');
person.set('age', 20);
Differences
Object only accepts string and symbol keys. Another types will be converted to string automatically.
Map
on the other hand accepts any type of key.We can iterate over the properties of a
Map
directly usingforEach
orfor ... of
statement:const styles = new Map();
styles.set('color', 'blue');
styles.set('fontSize', '12px');
styles.forEach((value, key) => console.log(key, '=', value));
// Output:
// color = blue
// fontSize = 12pxObjects are not iterable directly. In order to loop over the properties of an object, we have to use either
Object.keys
,Object.values
orObject.entries
to receives the list of keys, values or pairs of key and value.styles = {
color: 'blue',
fontSize: '12px',
};
Object.keys(styles).forEach((key) => console.log(key, '=', styles[key]));
// Output:
// color = blue
// fontSize = 12pxObject have special properties such as
constructor
,__proto__
, etc.let person = {};
person['constructor']; // ƒ Object() { [native code] }While
Map
only consists of what we define:let person = new Map();
person.get('constructor'); // undefinedJSON supports
Object
:const person = {};
person.name = 'Foo';
person.age = 20;
JSON.stringify(person); // "{"name":"Foo","age":20}"With
Map
, it's not possible to get the proper data when being serialized with JSON:const person = new Map();
person.set('name', 'Foo');
person.set('age', 20);
JSON.stringify(person); // "{}"
Good to know
Maps keep the order of items. It means when you loop over keys of a map, we will see the same order as when they're inserted to the map.
It's true for objects that only consists of string and symbol keys. The order of object's keys aren't kept if there is a key that needs to be converted to string.
let codes = { A: 65, B: 66, C: 67, 0: 48 };
codes; // {0: 0, A: 65, B: 66, C: 67}
Object.keys(codes); // ["0", "A", "B", "C"]
Good practice
If we want to store the key/value pairs without caring about serializing them in JSON, then use Map
. Looping through and getting the size of a map is more comfortable than doing with an object.
Object
should be used if we want to convert back and forth between raw data and JSON, or include a specific business logic:
const person = {
firstName: 'Foo',
lastName: 'Bar',
getFullName: function () {
return `\${this.firstName} \${this.lastName}`;
},
};