1

I’m writing a constructor for an ES2015 class that will accept either a Map or a plain old JavaScript object. If the input argument is a Map, the constructor will just store it, but if it’s a JS object, it should convert it to a Map, via, say, new Map(Object.keys(obj).map(k => [k, obj[k]])).

My question is: how can I safely tell whether an input argument is a Map or Object? I can test for a few Map-specific methods, but is there a more reliable and readable way? As far as I can tell, there’s no Map equivalent of Array.isArray.

Ahmed Fasih
  • 6,458
  • 7
  • 54
  • 95

2 Answers2

2

Use the instanceof operator:

const map = new Map()
     ,obj = {}
console.log(map instanceof Map) // true
console.log(obj instanceof Map) // false

Also, you can use Object.entries() if you want to convert an object to a Map:

new Map(Object.entries(obj))
Michał Perłakowski
  • 88,409
  • 26
  • 156
  • 177
1

You can use instanceof Map to test if it is a Map

user3
  • 740
  • 3
  • 15