2

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?

agm1984
  • 15,500
  • 6
  • 89
  • 113

2 Answers2

3

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.

Estus Flask
  • 206,104
  • 70
  • 425
  • 565
  • 3
    Notice that you'd use `Object.entries` only when you don't care about order. – Bergi Sep 04 '17 at 22:05
  • What is the nature of that Bergi? Is it because values could be removed and skew the order, or what kind of situations would this be critical to know? – agm1984 Sep 04 '17 at 23:05
  • @agm1984 Bergi refers to the fact that object keys are de jure unordered in JS, and their order cannot be relied on. They are de facto ordered in modern implementations, especially the ones that support ES6 and Map. While a map that was constructed from an array will be reliably ordered. – Estus Flask Sep 04 '17 at 23:40
  • Can one of you highlight an example that would illustrate when ordering would be affected? – agm1984 Sep 04 '17 at 23:50
  • @agm1984 When the code above is executed in older browser with polyfilled Map and Object.entries, like IE9. See https://stackoverflow.com/questions/9942132/order-of-iteration-differs-in-ie9 for example. – Estus Flask Sep 04 '17 at 23:57
  • Perfect, thanks. That makes perfect sense and additionally, I hope IE discontinues existing ASAP. – agm1984 Sep 05 '17 at 01:04
2

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

agm1984
  • 15,500
  • 6
  • 89
  • 113
  • 5
    Well, it's the first line in the documentation ... *"takes... an Array or other iterable object whose elements are key-value pairs"* as an argument ? – adeneo Sep 04 '17 at 20:49
  • Good eyes, reading documentation is a fine skill when haste is applied. – agm1984 Sep 04 '17 at 21:00
  • 1
    Sure it is, and most of us don't have that skill, I'll admit. Now you know that `Map` and `Set` both accept any iterable, meaning generally anything with a length, as an argument. Unfortunately that rules out most regular objects, which would have been easier to use as key->value pairs – adeneo Sep 04 '17 at 21:04