Background: The module query-string is for example able to parse key=value&hello=universe
to an object {key: 'value', hello: 'universe'}
. However, the module author has decided that the returned object does not have a prototype. In other words, this "bastard" object is created by Object.create(null)
.
Problem: It would be convenient to use parsed.hasOwnProperty('hello')
but that is not possible without the default object prototype. Of course, one could Object.prototype.hasOwnProperty.call(parsed, 'hello')
but I think we can all agree that such an expression is kill-immediately-after-birth ugly.
Question: How to nicely convert the prototypeless object to have a default object prototype and methods such as hasOwnProperty
? Additionally, can this be done without using the feared __proto__
or setPrototypeOf
?
It would be convenient to use
parsed.hasOwnProperty('hello')
but that is not possible without the default object prototype
The whole point of creating such a "bastard object" is that you cannot do that - what if someone sent a query string ?hasOwnProperty=oops
to your server?
How to nicely convert the prototypeless object to have a default object prototype and methods such as
hasOwnProperty
?
Don't. You should either use the long form with call
, or just go for the in
operator which does exactly what you need:
'hello' in parsed
In an ES6 environment, you might also want to convert the object to a proper Map
and use it has
method.