Map Object

  • ES6

  • Iterable like an array

  • It consists of key-value pairs like an object

  • However, unlike objects, maps can have any value as a key (Objects can only have strings or symbols as a key)

  • use methods to insert & delete values

      let jane = new Map();
    
      // insert with "set" method
      jane.set('id', 0);
      jane.set('name', 'jane');
      jane.set('major', 'international studies');
      jane.set('age', 27);
    
      // can also set with two dimentional array
      let amy = new Map([
          ['id', 1],
          ['name', 'Amy'],
          ['major', 'art'],
          ['age', 30]
      ]);
    
      //access Map with "get" method
      jane.get('age'); // 27
    
      // delete with "delete" method
      jane.delete('age'); // true (return boolean based on status)
    
      // clear all properties in Map with "clear" method
      jane.clear();
    

Why use?

  • Sometimes, using other data types than string or symbol as a key can be easier to understand

      const errorMsg = {
          404: "No such page",
          500: "Server error"
      }
    
      const errorMsg = new Map ([
          [404: "No such page"],
          [500: "Server error"]
      ])
    
      errorMsg.404 // unexpected number error
      errorMsg["404"] // "No such page"
      errorMsg.get(404) // "No such page"
    
  • using methods makes it easier to understand the intended action

  • can use for ...of loop

      let amy = new Map([
          ['id', 1],
          ['name', 'Amy'],
      ]);
    
      for (const [key, value] of amy) {
          console.log(key, value);
          // id 1
          // name Amy
      }