JSON.stringify then JSON.parse

I realized we keep doing JSON stringify then eventually parsing it back again and again to copy over objects. This does a dump “clone”, it ignores references and functions but is really fast. I wrote a Underscore.js or Lodash mixin just to do this.

[code lang=”javascript”]
/**
* This is the shortcut for JSON.stringify then parsing it back.
* Quick access to simple object copying.
* It does not copy functions!
*
* @author KahWee Teng
* @return {Object} Lodash mixin object.
*/
_.mixin((function() {
"use strict";
return {
copy: function(object) {
return JSON.parse(JSON.stringify(object));
}
};
}()));
[/code]

There’s just so many ways to doing a clone but this is by far the fastest but then again it depends on your needs. Dump clone I call this.

Leave a Reply

Your email address will not be published. Required fields are marked *