Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to detect if a variable is a pure javascript object

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

like image 562
KawaLo Avatar asked Nov 29 '22 21:11

KawaLo


2 Answers

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
like image 81
Naga Sai A Avatar answered Dec 05 '22 11:12

Naga Sai A


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 () {}));
like image 33
falinsky Avatar answered Dec 05 '22 13:12

falinsky