Search code examples
javascriptjsonjavascript-objects

Type of this is always object while checking for a valid Javascrip Object


I wrote a Prototype function in javascript to determine whether an entity is a valid Javascript object or not. Something like following


// Check if Object is Valid & Have at least one element

Object.prototype._isValidObject = function () {
    return this && typeof this === 'object' && !Array.isArray(this) && Object.keys(this).length >= 1;
};

The problem is it is returning TRUE for most of the values, like even for string, cause this is treated like an object for any value, like arrays, strings or json etc. There may be other ways to do this, but I need to make a prototype function for this. Please determine the correct way to Determine whether a value is a valid Javascript object having atleast one item. Thanks

EDIT By Valid Javascript / JSON Object I mean something like this:

{
  id:100,
  name:'somename',
  email:'[email protected]'
}

To be more precise following is what I want:


const j = {id:100,name:'somename', email:'[email protected]'};

const s = "{id:100, name:'somename', email:'[email protected]'}"; 

j._isValidObject(); // Should return true
s._isValidObject(); // Should return false

const j is valid for me cause it is an object having key-value pairs. const s is invalid for me cause it's a string representation of an object, not the object itself. const s can be converted to valid Object like const j, but right now const s is just a string.

EDIT I have found a solution, and posted it in answers. Though I am not marking it as accepted answer since I'm not sure whether it's the best way to do it. If somebody has a better solution, please post it. Thanks


Solution

  • I have found a solution, though I am not marking as accepted answer since I'm not sure whether it's the best way to do it. If somebody has a better solution, please post it. Thanks

    
    // Check if Object is Valid & Have at least one element
    
    Object.prototype._isValidObject = function () {
        return this
               && !(this instanceof String)
               && !Array.isArray(this)
               && Object.keys(this).length >= 1;
    };