skip to Main Content

I am trying to pass an object to another module; My object includes {__proto__: { value: 1}}.

const x = {
  __proto__: { value: 1 }
}

console.log(x)

what I expected as a result was

{__proto__: { value: 1 }}

but what I got was

{}

and I did try using "__proto__".

The only way I got it to work was by using

JSON.parse("{"__proto__": { "value": 1 }}")

but I really don’t think this is very performant solution (would require a lot of code configuring)

Is there a method to get it to be read like the parse and have

JSON.stringify(x) result in '{"__proto__": { "value": 1 }}' not '{}'

2

Answers


  1. The __proto__ key in object literals is treated specially and initialises the internal [[prototype]] of the new object. It does no matter whether you write {__proto__: …} or {"__proto__": …} for that. (This is related – by name only – to the Object.prototype.__proto__ getter/setter, but it is a separate and non-deprecated feature of object literals).

    To create a normal own property with the literal name __proto__, you can use a computed property name:

    const x = {
      ["__proto__"]: { value: 1 }
    };
    
    console.log(x);
    Login or Signup to reply.
  2. Certainly a very hacky solution but you could define custom JSON.stringify() logic using the replace? parameter. If a key of x is an empty string you can include the __proto__ manually.

    const x = {
      test: "test",
      __proto__: {value: 1}
    };
    
    const result = JSON.stringify(x, (key, value) =>
      !key ? {["__proto__"]: x.__proto__, ...value} : value
    );
    
    console.log(result);
    const parsed = JSON.parse(result);
    console.log(parsed);
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search