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
  • please share your object code and result when you stringify it and parse it Commented Nov 17, 2020 at 17:07

1 Answer 1

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

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.