Panu Logic Panu Logic - 6 months ago 27
Javascript Question

How to deal with JavaScript Objects which have no constructor

Node.js querystring.parse() method returns what looks like to be an object, but one without a constructor. According to :

"... The object returned by the querystring.parse() method does not prototypically inherit from the JavaScript Object. This means that typical Object methods such as obj.toString(), obj.hasOwnProperty(), and others are not defined and will not work."

This easily causes bugs because typically you would assume that every Object understands some basic methods like toString() and that it has a "constructor" which more or less tells us its "type".

What's the best way to handle these rather incapable Objects? I tried:

let myOb = new Object(dumbObject);

But that produces a result which does not have the toString() -method either and does not have the property 'constructor'.

What's the best way to turn these dumb objects into ordinarily behaving ones? And, why would anybody want to create such objects in the first place?

Answer Source

I think (from the top of my head)

let newObject = JSON.parse(JSON.stringify(dumbObject))

should work.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download