Clone, Parse and Stringify JavaScript objects using JSON.parse and JSON.stringify without loosing functions in deep object:
function localStringify(obj) {
return JSON.stringify(obj, function(key, val) { return (typeof val === 'function') ? val.toString() : val; });
return JSON.stringify(obj, function(key, val) { return (typeof val === 'function') ? val.toString() : val; });
}
function localParse(str) {
return JSON.parse(str, function(key, val) { return (typeof val === 'string' && val.substring(0,8) === 'function') ? eval('(' + val + ')') : val; });
}
function localParse(str) {
return JSON.parse(str, function(key, val) { return (typeof val === 'string' && val.substring(0,8) === 'function') ? eval('(' + val + ')') : val; });
}
function cloneObject(obj) {
if (obj === null || typeof obj !== 'object') {
return obj;
}
var temp = obj.constructor(); // give temp the original obj's constructor
for (var key in obj) {
temp[key] = cloneObject(obj[key]);
}
return temp;
}
if (obj === null || typeof obj !== 'object') {
return obj;
}
var temp = obj.constructor(); // give temp the original obj's constructor
for (var key in obj) {
temp[key] = cloneObject(obj[key]);
}
return temp;
}
Comments
Post a Comment