map

2021.12.22

Map in JavaScript

#JavaScript#basics
use client /components/post/reExport , date: , tags: [ ], imgUrl: , desc: , body: ( <> <p>Map is is a special type collection, like an object with keys of any data type.</p> <H>Object vs Map</H> <Code block jsx>{ }; let obj = {}; obj[john] = 123; obj // {[object Object]: 123} let map = new Map(); map.set(john, 123); map // [key: {name: }, value: 123] new Map([iterable]) let map = new Map() // creates the map // or let map = new Map([ [ ], [1, ], [true, ] ]); map.set(key, value) map.set( ) // a string key map.set(1, ) // a numeric key map.set(true, ) // a boolean key map.get(key) }</Code> - works, but isn’t the right way </li> </ul> </p> <Code block jsx>{ map.get(1); // }</Code> <H>Size</H> <Code block jsx>{ }</Code> <Hs>Delete</Hs> <ul> <li> <Code>{ }</Code> - removes the value by the key </li> <li> <Code>{ }</Code> - removes everything from the map </li> </ul> <H>Has</H> <ul> <li> <Code>{ }</Code> - returns true if the key exists, false otherwise </li> </ul> <H>Iteration</H> <p>Iteration goes in the same order as the values were inserted</p> <Code block jsx>{ , 500], [ , 350], [ , 50] ]); // returns iterable of keys, values & entries recipeMap.keys() // MapIterator { } recipeMap.values() // MapIterator{500, 350, 50} recipeMap.entries() // MapIterator{ => 50} // it’s used by default in for..of. for (let key of recipeMap.keys()) alert(key) // cucumber, tomatoes, onion for (let value of recipeMap.values()) alert(value) // 500, 350, 50 for (let entry of recipeMap) alert(entry) // cucumber,500 (and so on) // the same as of recipeMap.entries() recipeMap.forEach( (value, key, map) => { alert(\ ) // cucumber: 500 etc }) map.set( ).set(true, ) map // Map(3){ , true => }</Code> <H>{ }</H> <Code block jsx>{ ], [1, ], [true, ] ]); map.get( }</Code> <H>{ }</H> <Code block jsx>{ , age: 30 }; let map = new Map(Object.entries(obj)); map.get( }</Code> <H>{ }</H> <Code block jsx>{ , 1], [ , 2], ]) prices // { banana: 1, orange: 2, meat: 4 } let map = new Map(); let obj1 = {name: } let obj2 = {name: } map.set(obj1, ); map.set(obj2, ); obj1 = null obj2 = null map.size // 2 // bad let weakMap = new WeakMap(); let obj1 = {name: } let obj2 = {name: } weakMap.set(obj1, ); weakMap.set(obj2, ); obj1 = null obj2 = null weakMap.size // undefined // When obj gets garbage collected, weakMap will be removed as well // example from work where we get data from db, put it into Map and then check something against it const rowsFromDb = await q.execute() type AppId = { hpi: boolean; hsi: boolean } type RegisterAppIdMap = Map<number, AppId> const registerAppIdMap = rowsFromDb.reduce<RegisterAppIdMap>((map, row) => { const key = row.RegisterId const current = map.get(key) if (current === undefined) { map.set(key, { hpi: false, hsi: false, }) } else { if (row.AppId === ) { current.hpi = true } if (row.AppId === ) { current.hsi = true } } return map }, new Map()) // then pass registerAppIdMap further