Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a shorthand way to create a Map? [duplicate]

Take this code for example:

const db = new Map()
db.set('Neo4J', Neo4J.getDriver())
db.set('MongoDB', MongoDB.getDB())

Is there a way to shorten this like some kind of map literal?

like image 444
agm1984 Avatar asked Dec 03 '25 07:12

agm1984


2 Answers

I think I found the answer. This seems to work perfectly:

const db = new Map([
    ['Neo4J', Neo4J.getDriver()],
    ['MongoDB', MongoDB.getDB()]
])

The reason for needing this was that my DB connection drivers were exploding due to some keys containing functions as values.

Maps can handle this nicely: https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Map

like image 104
agm1984 Avatar answered Dec 05 '25 20:12

agm1984


Map constructor accepts an iterable:

An Array or other iterable object whose elements are key-value pairs (arrays with two elements, e.g. [[ 1, 'one' ],[ 2, 'two' ]]). Each key-value pair is added to the new Map; null values are treated as undefined.

A map can be defined with object literal via Object.entries which returns an iterable consisting of key-value pairs:

new Map(Object.entries({
  Neo4J: Neo4J.getDriver(),
  MongoDB: MongoDB.getDB()
}));

Object.entries is ES2017 and it is polyfillable in ES5 and ES6.

like image 41
Estus Flask Avatar answered Dec 05 '25 20:12

Estus Flask