2

How can I remove prototype fields from an object besides via this method ?

const input = {foo: 'bar', __proto__: {unwanted: 'things'}}
expect(JSON.parse(JSON.stringify(input))).toEqual({foo: 'bar'})  // true
// this works but is there a cleaner way ?
Lev
  • 13,856
  • 14
  • 52
  • 84
  • Possible duplicate of [How do I correctly clone a JavaScript object?](https://stackoverflow.com/questions/728360/how-do-i-correctly-clone-a-javascript-object) – Train Dec 17 '18 at 14:53
  • Its never a good idea to remove the `__proto__` of an object. It has all properties that make it an object, you should instead consider using `hasOwnProperty` – TheChetan Dec 17 '18 at 14:55

2 Answers2

2

it depends what you trying to achieve, but I would generally recommend .hasOwnProperty for checking whether the field is a prototype field

reference: MDN

1

you can use Object.create and pass to it null which will create clean object without prototype property, then you can create your properties for that object, but note that you can't use Object.prototype methods like hasOwnProperty(), toString(), valueOf() and so on

const input = Object.create(null);
input.foo = 'bar';
console.log(input);
Artyom Amiryan
  • 2,846
  • 1
  • 10
  • 22