How to remove __proto__ property from a JSON object? How to remove __proto__ property from a JSON object? mongoose mongoose

How to remove __proto__ property from a JSON object?


You can forego a prototype on an object simply by using Object.create(null) and defining the properties you wish to use.

var obj = Object.create(null);Object.defineProperty(obj, {  'foo': {    value: 1,    enumerable: true,  },  'bar': {    value: 2,    enumerable: false  }});// or...obj.foo = 1obj.bar = 2/* various checks */obj instanceof Object; // falseObject.prototype.isPrototypeOf(obj); // falseObject.getPrototypeOf(obj); // nullobj + ""; // TypeError: Cannot convert object to primitive value'toString' in obj; // falsefoo; // 1obj['bar']; // 2JSON.stringify(obj); // {"foo":1}{}.hasOwnProperty.call(obj, 'foo'); // true{}.propertyIsEnumerable.call(obj, 'bar'); // false

And in this approach, you no longer need to check for obj.hasOwnProperty(key)

for (var key in obj) {  // do something}

Read More: True Hash Maps in JavaScript

MDN: Object.defineProperty() &Object.create()

// with __proto__var obj = {} // equivalent to Object.create(Object.prototype);obj.key = 'value'console.log(obj)// without __proto__var bareObj = Object.create(null)Object.defineProperty(bareObj, {  'key': {    value: 'value',    enumerable: false,    configurable: true,    writable: true  }})// or... bareObj.key = 'value'console.log(bareObj)