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()
?
Advertisement
Answer
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