Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if a JavaScript object is Map or Set (ECMAScript 2015) [duplicate]

What are alternative / better ways to check if a JavaScript object is Map or Set than:

Object.getPrototypeOf(map) === Map.prototype Object.getPrototypeOf(set) === Set.prototype 
like image 942
krl Avatar asked Feb 09 '16 17:02

krl


People also ask

How do you check if an Object is a Map in JavaScript?

Use the instanceof operator to check if an object is a Map - myObj instanceof Map . The instanceof operator returns true if the prototype property of a constructor appears in the prototype chain of the object.

How do you compare Object and Map?

Few basic differences are as follows: In Object, the data-type of the key-field is restricted to integer, strings, and symbols. Whereas in Map, the key-field can be of any data-type (integer, an array, even an object!) In the Map, the original order of elements is preserved.

What is difference between Map and set in JavaScript?

In Map() , key can be any type [String, number, Object] but in regular object key must be a string type. Set is one dimensional unique array, however Map is 2D and has key-value pair, where key shall be unique.

Is ES6 a Map?

ES6 provides us a new collection type called Map, which holds the key-value pairs in which values of any type can be used as either keys or values. A Map object always remembers the actual insertion order of the keys. Keys and values in a Map object may be primitive or objects. It returns the new or empty Map.


1 Answers

Use instanceof:

var foo = new Set; foo instanceof Set; // True! foo instanceof Map; // False! 
like image 79
amphetamachine Avatar answered Nov 03 '22 12:11

amphetamachine