Check that value is object literal?

I have a value and want to know if it's an iteratable object literal, before I iterate it.

How do I do that?


This should do it for you:

if( Object.prototype.toString.call( someObject ) === '[object Object]' ) {
    // do your iteration
}

From ECMAScript 5 Section 8.6.2 if you're interested:

The value of the [[Class]] internal property is defined by this specification for every kind of built-in object. The value of the [[Class]] internal property of a host object may be any String value except one of "Arguments", "Array", "Boolean", "Date", "Error", "Function", "JSON", "Math", "Number", "Object", "RegExp", and "String". The value of a [[Class]] internal property is used internally to distinguish different kinds of objects. Note that this specification does not provide any means for a program to access that value except through Object.prototype.toString (see 15.2.4.2).


You could also do something like:

    if (someObject.constructor == Object) {
        // do your thing
    }

you can read more about it here


I think a function like this should be native, just like Array.isArray:

Object.isObject = function(obj) {
    return obj && obj.constructor === this || false;
};

This one doesn't make function calls nor string comparisons, and doesn't reference global objects (like Object), so it should be quite fast. I don't think this will used in performance intensive tasks though, but whatever.

I'm not totally convinced about the name... maybe something like Object.isLiteral would be better.

It can cause problem with host objects, though, but I don't have a test ready.


Say you have some testvar and want to see if it is an object, but not an array or null (these are both of type Object). You can do the following

testVar instanceof Object && !Array.isArray(testVar) && testVar !== null

If you use obj instanceof Object or typeof obj === "object" you get false positives on things like new Number(3) and arrays ([1,2,3]).

Using o.constructor === Object is great, however there's a weird edge case of Object.create(null) – which does, in fact, give you a plain object, albeit not one created in a "normal" way. Conceptually it gives a valid, normal, undecorated object. We check for this case with Object.getPrototypeOf(o) === null which will only hold true for the above undecorated object type.

The !!o converts null or undefined to false. People were complaining about it above, and honestly o && ... is more succinct and unless you're serializing it doesn't matter. Nevertheless, I included it.

function isObject(o) {
  return o && o.constructor === Object
}

function isObject1(o) {
  return !!o && o.constructor === Object
}

function isObject2(o) {
  // edge case where you use Object.create(null) –– which gives an object {} with no prototype
  return !!o && (Object.getPrototypeOf(o) === null || o.constructor === Object)
}