Log in

No account? Create an account

Previous Entry

Let’s say you have some object, and want to made a “backup” before modifying it. The easiest way to do this is to use JSON.stringify and JSON.parse. First function serializes an object into json string, and the second one parses json string into object. Be aware that only properties will be copied and not methods. Example:

var original = {
name: "John",
secondName: "Doe",
has: ["house", "car", "yacht"],
doSomething: function() {}

var backup = JSON.parse(JSON.stringify(original));

original.name = "Ivan";
original.secondName = "Ivanov";


As caniuse.com reports, this feature is available  in all modern browsers, so it’s safe to use.

Originally published at Gennady's blog. Please leave any comments there.