Akseli Palén Akseli Palén - 1 year ago 100
Javascript Question

How to create a JS object with the default prototype from an object without a prototype?

Background: The module query-string is for example able to parse

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

Problem: It would be convenient to use
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
? Additionally, can this be done without using the feared

Answer Source

I can't say I've ever done this before, but here's one way to do it

let bastard = Object.create(null);
bastard.father = 'vader';

let adopted = Object.assign({}, bastard);
console.log(adopted.hasOwnProperty('father')); // => true

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