3

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?

1

2 Answers 2

6

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.

Sign up to request clarification or add additional context in comments.

Comments

3

You can use obj.constructor.name:

var tst = 1 > 0;
var num = 3.141592;
var obj = {a:1};
var arr = [1,2];
var dat = new Date();
var xhr = new XMLHttpRequest();

console.log(tst.constructor.name);
console.log(num.constructor.name);
console.log(obj.constructor.name);
console.log(arr.constructor.name);
console.log(dat.constructor.name);
console.log(xhr.constructor.name);

I'm not sure how well this will work with e.g. the Mongo type. Please try and let us know!

1 Comment

Just tried it with the ISODate coming from MongoDB and it gave me Date Good enough!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.