Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if is an Object [closed]

Tags:

javascript

I need to check if a variable is a pure Object instance. For example: a HTMLElement is instanceof Object. But I really need to check if it is only an Object, like {a: true, b: false} is. It not can validate an Array.

Note: I can use newer features of Chrome, if better.

like image 417
David Rodrigues Avatar asked Feb 27 '13 02:02

David Rodrigues


2 Answers

Check the constructor. Seems to work in all browsers

if (a.constructor === Object)
// Good for arrays
([]).constructor === Object => false
// Good for HTMLElements
document.body.constructor === Object => false
like image 116
Juan Mendes Avatar answered Sep 27 '22 01:09

Juan Mendes


var proto = Object.getPrototypeOf(obj);

var protoproto = Object.getPrototypeOf(proto);

if (proto === Object.prototype && protoproto === null) {
    //plain object
}

If you'll be creating objects with a null prototype, you could get rid of the protoproto, and just compare proto to Object.prototype or null.

The danger of that is that it doesn't guard against being passed Object.prototype itself, perhaps causing accidental extensions of Object.prototype.


A little shorter and safer like this:

var proto = Object.getPrototypeOf(obj);

if (proto && Object.getPrototypeOf(proto) === null) {
    // plain object
}

like image 41
the system Avatar answered Sep 27 '22 01:09

the system