I have a function I need to pass an object to. I use typeof
operator to make a check before processing. But looking at this link, it appears that many javascript instances, such as array or regex, are typed as Objects.
I need my argument to be a pure object (like this : {key: value, . . .}
).
Is their any way I can check if a variable is pure object, without having to run specific test for each Object instance, like Array.isArray()
?
To achieve expected result, use below option of finding constructor name to check if variable is pure javascript Object or not
As per MDN,
All objects (with the exception of objects created with Object.create(null)) will have a constructor property. Objects created without the explicit use of a constructor function (i.e. the object and array literals) will have a constructor property that points to the Fundamental Object constructor type for that object.
Please refer this link for more details on constructor property - https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/constructor
var x = {a:1,b:2};
var y = [1,2,3];
console.log(x.constructor.name === "Object")//x.constructor.name is Object
console.log(y.constructor.name === "Object")//y.constructor.name is Array
You can check prototypes:
function isPureObject(input) {
return null !== input &&
typeof input === 'object' &&
Object.getPrototypeOf(input).isPrototypeOf(Object);
}
console.log(isPureObject({}));
console.log(isPureObject(new Object()));
console.log(isPureObject(undefined));
console.log(isPureObject(null));
console.log(isPureObject(1));
console.log(isPureObject('a'));
console.log(isPureObject(false));
console.log(isPureObject([]));
console.log(isPureObject(new Array()));
console.log(isPureObject(() => {}));
console.log(isPureObject(function () {}));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With