If you just want to check for "normal" pure objects (the ones created by {...}, JSON.parse(...), etc.), then this function will work
function is_pure_object(val) {
return val ? Object.getPrototypeOf(val)==Object.prototype : false
}
If you also need to handle objects without a prototype (very rare, only created by Object.create(null)), then you need to do an additional check:
function is_pure_object2(val) {
if (!val)
return false
let proto = Object.getPrototypeOf(val)
return proto == Object.prototype || proto == null
}
Notes about other solutions:
- Checking
val.constructor is not reliable:
- fails on values like
{constructor: 1}
- fails on
Object.create(null)
- error if
Object.prototype.constructor is modified
Object.getPrototypeOf(val).isPrototypeOf(Object) is also not ideal:
- error on
Object.create(null)
- error if
Object.prototype.isPrototypeOf is modified
(Object.prototype being modified is unlikely, but I've dealt with it before)
Boolean(obj) && obj.constructor === Objectbe good enough for you, knowing that even objects that are instances of any class wouldn’t be matched?Object.getPrototypeOf(variable) === Object.prototypeHTMLElement(etc), you can useinstanceof. The "plain object" is theelsecase.