Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to test that a variable is type Map or Array?

In ES6, how can I test if a variable is an Array or a Map?

instance.constructor.name === 'Map' is a risky habit, even if it's core type, doing this with your own class when minified will break the test.

What is the most reliable way to verify that the variable is an instance of Map

like image 533
Dimitri Kopriwa Avatar asked Dec 01 '22 09:12

Dimitri Kopriwa


2 Answers

const getType = obj => Object.prototype.toString.call(obj).slice(8, -1);

const isArray = obj => getType(obj) === 'Array';

const isMap = obj => getType(obj) === 'Map';


const arr = [];

console.log(isArray(arr)); // true


const map = new Map();

console.log(isMap(map)); // true
like image 149
fyasir Avatar answered Dec 03 '22 23:12

fyasir


Instead of checking the constructor's .name (string) property, just check whether the constructor itself is === Map:

const m = new Map();
console.log(m.constructor === Map);
like image 40
CertainPerformance Avatar answered Dec 04 '22 01:12

CertainPerformance