1

I know that JSON.stringify doesn't preserve methods. I have a bridge object that has many fields and methods. If I want to save the bridge's fields I stringify it. When I parse it back the object doesn't contain methods so when I set the bridge = JSON.parse(savedBridgeString) it causes many errors since the bridge object methods are gone. Is there a way to set only the fields equal to the parsed savedBridgeString?

Thanks.

var Bridge = function()
{
    this.length = 15;
    this.height = 2;
    this.changeHeight = function(newHeight)
    {
        this.height = newHeight;
    }
}
var bridge = new Bridge();
var bridgeStringified = JSON.stringify(bridge);
bridge = JSON.parse(bridgeStringified);
//bridge.changeHeight(3); //<--this gives error

The bridgeStringified is "{\"length\":15,\"height\":2}" at the end.

1 Answers1

1

Create a new object to get the field defaults + methods. Copy in the parsed values. You can do this automatically with Object.assign, or iterate over the parsed data manually.

let b = new Bridge();
let bData = JSON.parse(savedBridgeString);
b = Object.assign(b,bData);

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/assign

James L.
  • 12,893
  • 4
  • 49
  • 60