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?
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?
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.
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