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 = 1
obj.bar = 2

/* various checks */

obj instanceof Object; // false
Object.prototype.isPrototypeOf(obj); // false
Object.getPrototypeOf(obj); // null
obj + ""; // TypeError: Cannot convert object to primitive value
'toString' in obj; // false
foo; // 1
obj['bar']; // 2
JSON.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)


You don't need to remove that. It doesn't cause any trouble/problem.

You can use like this.

$.each(data, function(k, v) {
    console.log(k, v);
});

Sending __proto__ out from the server can create a JSON object that may break things if the keys are transferred to another object without removing __proto__ or leak sensitive data.

It's unusual that it would appear in encoded JSON as it is usually ignored. That suggests there might be a problem or kludge elsewhere. It's possible the library you're using it leaking it by accident or making use of it. It may be alright to make use of it in a closed system but it should not be allowed either into or out of the system.

// If is optional.
if('__proto__' in obj)
    // This may cause unintended consequences.
    delete(obj.__proto__);

On receiving data you should also be very careful that it doesn't contain a __proto__ property. This can crash or compromise the server if that key is copied over to another object.

If creating your own object there are tricks to change it's behaviour such as using defineProperty but these tricks tend not to eliminate the problem entirely.