skip to Main Content

How can an object created with a null prototype using Object.create(null,{...}) be stored in a database and restored?

And, if all you are given is the stringified object, can it be parsed to a desired prototype?

JSON.parse() returns an object with the default prototype.

For example,

let nullObj = Object.create(null, {
  a: {
     value: 10,
     writable: true
  },
  b: {
     value: 'Text'
  }
});

let jsonObj = JSON.parse('{"a":10,"b":"Text"}');

2

Answers


  1. You can use Object.assign() with the base object created by Object.create(null) and the object parsed from the JSON string.

    You can also set the prototype of the parsed object using Object.setPrototypeOf().

    Here’s a demonstration of both approaches:

    const o1 = Object.create(null, {
      a: {
        value: 10,
        writable: true,
      },
      b: {
        value: "Text",
      },
    });
    
    const json = '{"a":10,"b":"Text"}';
    
    const o2 = JSON.parse(json);
    
    const o3 = Object.assign(
      Object.create(null),
      JSON.parse(json),
    );
    
    const o4 = JSON.parse(json);
    Object.setPrototypeOf(o4, null);
    
    console.log("o1", Object.getPrototypeOf(o1) === null); // true
    console.log("o2", Object.getPrototypeOf(o2) === Object.prototype); // true
    console.log("o3", Object.getPrototypeOf(o3) === null); // true
    console.log("o4", Object.getPrototypeOf(o4) === null); // true
    Login or Signup to reply.
  2. to be able to store and restore an object created by Object.create(null,{...}) you would have to use [JSON.stringify()]
    the code would look like this

       // Storing
       const objWithNullPrototype = Object.create(null);
       objWithNullPrototype.property1 = 'value1';
       objWithNullPrototype.property2 = 'value2';
    
       const jsonString = JSON.stringify(objWithNullPrototype);
    
       // Restoring
       const restoredObject = JSON.parse(jsonString);
    
       console.log(restoredObject.property1); // 'value1'
       console.log(restoredObject.property2); // 'value2'
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search