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)