Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how can I remove prototype fields from an object?

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 ?
like image 572
Lev Avatar asked Sep 13 '26 08:09

Lev


2 Answers

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

reference: MDN

like image 160
Kamila Korzec Avatar answered Sep 15 '26 21:09

Kamila Korzec


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);
like image 40
Artyom Amiryan Avatar answered Sep 15 '26 23:09

Artyom Amiryan