JavaScript – Is Map better than Object?

What are differences between Map and Object?

  • Key in Object must be “String” or “Symbol” whereas Key in Set can be anything
  • To iterate over the keys, values or entries in an object, you must either convert them to an array, using Object.keys() , Object.values() or Object.entries() or use a for ... in loop. Because objects are not directly iterable.
    But Maps are directly iterable. The order of iteration is the same as the order of insertion. To iterate over a Map’s entries, you can use a for ... of loop or the forEach method
            for (let [key, value] of a map) {
                console.log(key);
                console.log(value);
            };
            map.forEach((key, value) => {
                console.log(key);
                console.log(value);
            });

When Map is better than Object?

  • Finding entries
  • Adding entries
  • Deleting entries

When Map is worse than Object?

Adding entries to Map is slower than adding entries to Object

let obj = {}, map = new Map(), n = 1000000;
console.time('Map');
for (let i = 0; i < n; i++) {
  map.set(i, i);
}
console.timeEnd('Map');
console.time('Object');
for (let i = 0; i < n; i++) {
  obj[i] = i;
}
console.timeEnd('Object');

// Object: 32.143ms
// Map: 163.828ms (5 times slower)

How to use Map()?

Convert Json string to Map()

const jsonObj = JSON.parse(jsonString)
const jsonMap = new Map(Object.entries(jsonObj))

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, otherwise, return false.
  •  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.

Be the first to comment

Leave a Reply

Your email address will not be published.


*