Questions tagged [es6-map]

The ECMAScript 6 Map object holds key-value pairs that can be iterated through by looping. To use this tag, the post must be using ECMAScript 6 and must concern the use of how to use Map properly.

Syntax

To create a map:

const myMap = new Map();  //Map(0) 

This will create a new empty map object. The Map() constructor takes one optional parameter. For example, it can take an array of key/value pairs:

const myArr = [[1, 'one'], [2, 'two']];
const myMap = new Map(myArr);  //Map(2) {1 => "one", 2 => "two"}

This creates a map object with key 1 with a value of 'one' and key 2 with a value of 'two'. This is also possible with an iterable object:

const myIt = {
*[Symbol.iterator]() {
    yield [1, 'one'];
    yield [2, 'two'];
}};
const myMap = new Map(myIt); //Map(2) {1 => "one", 2 => "two"}

Again, this creates a map with the same structure as the last example.

Note that any value, from primitives to objects, can be used as either a key or a value. This includes NaN (Not a Number):

const myArr = [[NaN, 'one']];
const myMap = new Map(myArr);  //Map(1) {NaN => "one"}

This creates a map with a key of NaN with the value of "one". Even though NaNs are indistinguishable from each other, you cannot use them for multiple keys:

const myArr = [[NaN, 'one'], [NaN, 'two']];
const myMap = new Map(myArr);  //Map(1) {NaN => "two"}

This will only create one key of NaN where the last value associated with NaN will be in the map.

There are also getters and setters for the Map Object:

const myMap = new Map();  //Map(0)
myMap.set(1, "one");    //Map(1) {1 => "one"}
myMap.set(2, "two");    //Map(2) {1 => "one", 2 => "two"}
myMap.get(1);           //one
myMap.get(2);           //two

You can also create a map with mixed keys:

const myMap = new Map();
myMap.set(1, "one");
myMap.set("two", 2);
myMap.set(function () { return 3; }, "three")

This will create a map with a key of integer 1 with string value "one", a key of string "two" with an integer value of 2, and a key of an anonymous function with a string value of "three". However, while this works with setting, getting the last key will be impossible unless you define it outside the map first:

const myFunc = function () { };
const myMap = new Map();
myMap.set(1, "one");
myMap.set("two", 2);
myMap.set(myFunc, "three")
myMap.get(myFunc);    // three

To iterate through the map, you can use destructuring with the for...of loop:

for (var [key, value] of myMap) {
    console.log(key + ' = ' + value);
}

Or the forEach loop can be used as well:

myMap.forEach(function(value, key) {
    console.log(key + ' = ' + value);
});

Both examples will output the keys along with their values.

Reference

developer.mozilla.org

91 questions
2
votes
5 answers

How can I map a 2 different arrays with the same component values?

const App = () => { const courses = [ { name: 'Half Stack application development', id: 1, parts: [ { name: 'Fundamentals of React', exercises: 10, id: 1 }, { …
miro_muras
  • 33
  • 6
2
votes
0 answers

How do I get the value of the key if the key in the Map is an array?

Only the reference to the same object, the Map structure will treat it as the same key. If the key in Map is an array, the get method cannot read the key and returns undefined. const map = new Map(); map.set(['a'], 111); map.get(['a']) //…
crane
  • 31
  • 6
2
votes
1 answer

Getting Heap out of memory Error even when available heap memory is much larger than used

I'm getting the following error even when I run node with high heap memory using the following command: node --max-old-space-size=8000 manipulateFiles.js FATAL ERROR: invalid table size Allocation failed - JavaScript heap out of memory 1: 0x8dc510…
tito.300
  • 976
  • 1
  • 9
  • 22
2
votes
1 answer

Does clearing a map aid with garbage collection?

I recently noticed that my colleague tends to clear any maps before they get dereferenced, such as at the end of a function. His argument for this is that it's good practice for garbage collection, and I was curious if this is true or a case of…
2
votes
1 answer

Unexpected Set trap behavior in ES6 Proxy

let ar = []; let p = new Proxy(new Map(), { get: (o, k) => { ar.push(1) return Reflect.get(o, k).bind(o) }, set: (o, k, v) => { ar.push(2) return Reflect.set(o, k, v) } }); p.set(1, 2) p.get(1) console.log(ar) //Outputs [1,1] I am trying…
CoodleNoodle
  • 324
  • 3
  • 17
2
votes
3 answers

React: How to show message when result is zero in react

How to show No Result message when the search result is empty with in map() ? export class Properties extends React.Component { render () { const { data, searchText } = this.props; const offersList = data …
Mo.
  • 26,306
  • 36
  • 159
  • 225
1
vote
0 answers

Type error - .push is not a function when using .map

I have this function in my codebase, const renderList = (listItems) => listItems.map((page) => html`
  • ${page.label}
  • `); const renderSection = (siteMapContent) => html`
    Udders
    • 6,914
    • 24
    • 102
    • 194
    1
    vote
    1 answer

    What is the best way to use a list as a key in JavaScript?

    Let say we have a map in JS as below. const someMap = new Map(); someMap.set(["Jack", "Mathematics"], "Fee=₹120000"); someMap.set(["Alyne", "Science"], "Fee=₹90000"); // Going to be undefined because the lists are compared by…
    kaushalpranav
    • 1,725
    • 24
    • 39
    1
    vote
    1 answer

    How to eleminate the duplicate objects within the array in angular

    I am trying to filter the duplicate values and get the unique values as an array of object. I don't know how to get the unique value based on the color. so below is my data: [ { "code": "xxxx1", "priceData": { …
    1
    vote
    1 answer

    How is object lookup implemented by Map.get(obj) in the javascript v8 engine?

    I'm curious about the internals of v8 and how Map is implemented under the hood. Contrasting Maps, javascript objects cannot have objects as keys. As far as I understand it Maps implement lookup in the classic hash map fashion. Some hashing function…
    david_adler
    • 9,690
    • 6
    • 57
    • 97
    1
    vote
    1 answer

    How do I dynamically add method to javascript object without getting this weird error

    I have an array of javascript objects, let headers = [ { text: 'something', value: 'something else' }, { text: 'something1', value: 'something else1' }, // etc.. ] I want to loop through the array and add a method to each…
    1
    vote
    1 answer

    How do I iterate through an ES6 Map in order?

    The default iteration order through an ES6 map is insertion order. How do you iterate through it in numeric/lexicographic order?
    Timmmm
    • 88,195
    • 71
    • 364
    • 509
    1
    vote
    0 answers

    How Map stores keys

    I was reading about lit-html and how it works here. But i could not understand how they can use the strings argument as cache-key. I have read about Map in mdn but i didnt found anything that explains how Map get and set works. My question how the…
    hawks
    • 861
    • 1
    • 8
    • 20
    1
    vote
    3 answers

    Map Filter in React. Objects are not valid as a React child. If you meant to render a collection of children, use an array instead

    function Main(){ // create an array that holds objects const people = [ { firstName: 'Fathi', lastName: 'Noor', age: 27, colors: ['red', 'blue'], bodyAttributes: { …
    user3657273
    • 39
    • 2
    • 8
    1
    vote
    1 answer

    Reactjs Material load defaultValue in TextField & Cannot read property 'map' of undefined

    I have two issue here. Cant load defaultValue in TextField. I'm using reactjs material When I start typing in input TextField. It's throwing error in below Cannot read property 'map' of undefined Can anyone tell where I made…
    SKL
    • 1,243
    • 4
    • 32
    • 53