Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to detect "different object types" in JavaScript? (array vs Json vs Date etc...)

Tags:

javascript

For the purpose of creating a condition while recursively iterating over a JSON object, I'm trying to find a clean way to differentiate different object types.

Consider this:

var aJSON     = {"foo" : 1, "bar" : 2};
var anArray   = [1,2,3,4,5];
var aDate     = new Date('2013-03-10T02:00:00Z');
var anISODate = user.timesTheyLoggedIn[0] // comes from MongoDB

console.log(typeof aJSON);     // object
console.log(typeof anArray);   // object
console.log(typeof aDate);     // object
console.log(typeof anISODate); // object

All types of objects are 'objects' with no more info.

For now, my use case only requires detecting an ISODate object, so I'm taking advantage of ISODate objects having a resetTime function to differentiate them from others, like so:

if (typeof(val) === "object" && val.resetTime === undefined) { //do stuff...

But there must be a cleaner, better way to detect what kind of object an object is, a val.isArray() kinda thing...

How would do it?

PS: "different object types" is in quotes because there really is only one object type in JS, right?

like image 849
Félix Paradis Avatar asked Dec 07 '25 06:12

Félix Paradis


1 Answers

If they are a class, like Date, you can use instanceof like so:

(new Date() instanceof Date)

Which evaluates to true.

The same can be applied to arrays as long as you don't use iframes:

([] instanceof Array)

But you have to find your own way for types that aren't classes.

If you don't have to stick to plain JavaScript, you could switch to Typescript, where you can also describe types.

like image 133
lilezek Avatar answered Dec 09 '25 19:12

lilezek