A veces salen unos errores al clonar objetos en javascript, por ejemplo: "circular reference".
Pero encontré hace poco la manera de clonarlos sin problemas... gracias jquery.
La solución es:
var objetoClonado = $.extend(true, {}, objetoAClonarConFunciones);
MEJOR IR A LA FIJA CON EL SIGUIENTE CÓDIGO: GRACIAS A STACKOVERFLOW.
Actualización.... creo que este si le funcionará sin problemas. Aunque no es tan automático, les puede servir la funcion:
function objetoAJSONString(censor) {
var i = 0;
return function(key, value) {
if(i !== 0 && typeof(censor) === 'object' && typeof(value) == 'object' && censor == value)
return '[Circular]';
if(i >= 29) // seems to be a harded maximum of 30 serialized objects?
return '[Unknown]';
++i; // so we know we aren't using the original object anymore
return value;
}
}
y se utiliza así:
JSON.stringify(objetoConFuncionesOReferenciaCircular, objetoAJSONString(objetoConFuncionesOReferenciaCircular))
FIN... AHORA SI DISFRUTEN
ENCONTRÉ OTRA OPCIÒN: Esto parece que no esta servido en internet, pero aquí lo dejo. De nuevo, gracia a stackoverflow:
JSON.stringifyOnce = function(obj, replacer, indent){
var printedObjects = [];
var printedObjectKeys = [];
function printOnceReplacer(key, value){
if ( printedObjects.length > 2000){
//return 'object too long';
}
var printedObjIndex = false;
printedObjects.forEach(function(obj, index){
if(obj===value){
printedObjIndex = index;
}
});
if ( key == ''){ //root element
printedObjects.push(obj);
printedObjectKeys.push("root");
return value;
}
else if(printedObjIndex+"" != "false" && typeof(value)=="object"){
if ( printedObjectKeys[printedObjIndex] == "root"){
return "(pointer to root)";
}else{
return "(see " + ((!!value && !!value.constructor) ? value.constructor.name.toLowerCase() : typeof(value)) + " with key " + printedObjectKeys[printedObjIndex] + ")";
}
}else{
var qualifiedKey = key || "(empty key)";
printedObjects.push(value);
printedObjectKeys.push(qualifiedKey);
if(replacer){
return replacer(key, value);
}else{
return value;
}
}
}
return JSON.stringify(obj, printOnceReplacer, indent);
};
Espero les sirva.
Sean felices! :) Y siéntanse libres de opinar ;)
No hay comentarios:
Publicar un comentario