Carl Patenaude Poulin Carl Patenaude Poulin - 1 year ago 70
Javascript Question

Check if Iterable is a Map

I have an object which I know to be iterable. I want to do something different depending on whether it's a

Map
or not. Here is an incomplete solution:

function toList(iterable) {
let results = [];
if (/* iterable is a map */) {
for (let elem of iterable) {
elem[1].key = elem[0];
results.push(elem[1]);
}
} else {
for (let elem of iterable) {
results.push(elem);
}
}
return results;
}


Is there anything I could use to authoritatively check whether
iterable
is a Map or not?

Answer Source

The keyword you are looking for here is instanceof. It checks whether another Object is in the prototype chain of an object.

So in your case:

if (iterable instanceof Map) {
    ...
}