-4

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:'maiL@mail.com'
}

To be more precise following is what I want:


const j = {id:100,name:'somename', email:'maiL@mail.com'};

const s = "{id:100, name:'somename', email:'maiL@mail.com'}"; 

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

  • 2
    Please define what exactly "a valid JSON object" is first. – deceze Jul 07 '20 at 08:42
  • Does this answer your question? [How to check if a string is a valid JSON string in JavaScript without using Try/Catch](https://stackoverflow.com/questions/3710204/how-to-check-if-a-string-is-a-valid-json-string-in-javascript-without-using-try) – Wimanicesir Jul 07 '20 at 08:44
  • Note: Check second answer, not the accepted. – Wimanicesir Jul 07 '20 at 08:45
  • 2
    By definition, any Javascript object is a valid object, and since almost anything is an object, pretty much everything is. It might be easier to ask what exactly you want to *exclude*. – deceze Jul 07 '20 at 08:47
  • @Wimanicesir that's for checking whether a string is a valid JSON or not. In my question the value can be a JSON already, I need to confirm it just. If it's a string, whether it's a json string, it should return false, if it's already a JSON object, it should return true. I don't want to confirm whether a string is in JSON format or not – Himanshu Agrawal Jul 07 '20 at 08:49
  • Because your prototype is on `Object`, everything is being *cast* to an `Object`. I modified your function like so: `Object.prototype._isValidObject = function () { return typeof this; };`, then I ran `"hello word"._isValidObject()` - this outputs `Object`, so you can't use this method with `typeof` – Luke Jul 07 '20 at 08:50
  • @Luke yes, you are right. So what's the getaway with this. – Himanshu Agrawal Jul 07 '20 at 08:51
  • What about `JSON.parse('"Foo"')`. The result is `"Foo"`, a Javascript string, but not JSON… – deceze Jul 07 '20 at 08:56
  • 1
    Now that we have come to an understanding about what a JavaScript object is, you still need to define what constitutes a "valid" JavaScript object. Is a date object valid? Is a DOM element object valid? – Robby Cornelissen Jul 07 '20 at 09:09
  • 1
    [Turning this around,](http://xyproblem.info) what problem is it you're trying to solve? You don't know whether any one particular variable holds a JSON string that must be decoded or an already decoded value? As illustrated above with my string example, that's a bad situation to find yourself in, since the question isn't really answerable for strings in general. This is a problem that would need to be solved with a better definition of your data flow; i.e. you *should know* at any one point whether you expect to have JSON or a Javascript value. You shouldn't need to guess at all. – deceze Jul 07 '20 at 09:12
  • @RobbyCornelissen, please check the example i have given in the end of my EDIT section. I just want that. 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. – Himanshu Agrawal Jul 07 '20 at 09:13
  • What you are likely looking for is whether it is a POJO (plain old javascript object), See https://github.com/jonschlinkert/is-plain-object and the [source](https://github.com/jonschlinkert/is-plain-object/blob/master/index.js). Read the usage to see exactly which cases it supports and which not. – Gabriele Petrioli Jul 07 '20 at 09:14

1 Answers1

0

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;
};

  • 1
    `console.log(console._isValidObject());` Nobody but you can answer your question because you have still not shared your definition of what constitutes a valid object. – Robby Cornelissen Jul 07 '20 at 09:30
  • I have clearly mentioned in my example in edit section that for me a valid object is one which has a key-value relation, like a hash-map, whose values can be accesses by accessing the key-name as an index. Like we access a class member in any oops programming language by creating the object of the class. It shouldn't be the string representation, but an actual object – Himanshu Agrawal Jul 07 '20 at 09:35
  • The problem, *any* Javascript object fits that definition (except for special values like `undefined`). – deceze Jul 07 '20 at 09:44
  • That i realized. That's why i am asking for a solution to differentiate between string representation and bytecode object. var obj = new C1(); var str = "class C1{}";. We can't say str is an object of class C1. It's just a string representation. obj is an object. So there is a difference between var s = {} and var j = "{}". – Himanshu Agrawal Jul 07 '20 at 09:53
  • @Himanshu Yes, so the only clear rule appears to be: "is it a string?" But again, if it is a string, that doesn't automatically mean it's a JSON string either, it could very well just be a… string. To give a *useful* solution to your question, we'd need to know to what extent you have considered this and how relevant that concern is. – deceze Jul 07 '20 at 10:17