You can write this function to convert any object for string
.
See this Jsfiddle example of the function below
function ToString(obj) {
clearTimeout(window.ToStringTimeout);
var result;
var ident = arguments.length >= 2 ? arguments[1] : undefined;
if (obj == null) {
result = String(obj);
}
var objString;
try {
objString = obj.toString();
} catch (err1) {
try {
objString = String(obj);
} catch (err2) {
try {
objString = obj + "";
} catch (err3) {
objString = "ERROR CONVERT STRING";
}
}
}
if (!result) {
window.ToStringRecursive = window.ToStringRecursive ? window.ToStringRecursive : [];
if (window.ToStringRecursive.indexOf(obj) >= 0) {
result = obj ? (typeof(obj) == "string" ? "\"" + obj + "\"" : objString) : obj;
} else {
window.ToStringRecursive.push(obj);
}
if (!result) {
switch (typeof obj) {
case "string":
result = '"' + obj + '"';
break;
case "function":
result = obj.name || objString;
break;
case "object":
var indent = Array(ident || 1).join('\t'),
isArray = Array.isArray(obj);
result = '{[' [+isArray] + Object.keys(obj).map(
function(key) {
return '\n\t' + indent + key + ': ' + ToString(obj[key], (ident || 1) + 1);
}).join(',') + '\n' + indent + '}]' [+isArray];
break;
default:
result = objString;
break;
}
}
}
window.ToStringTimeout = setTimeout(function() {
delete window.ToStringTimeout;
delete window.ToStringRecursive;
}, 100);
return result;
}
Test using this:
console.log(ToString(new MyObject()));
To display this:
{
prop1: "Olá, Mundo!",
prop2: "Hahahaha",
recursivo: [object Object],
funcao: function () { return "retorno da função"; }
}
Note that when a property is recursive it does not display again because it would give an infinite loop.
EDIT1: To work on Nodejs declare var window = { };
That way you modify the object, that’s it?
– Sergio Cabral
@Not sergiocabral. I create a temporary variable
_obj
and I don’t touch anythingobj
.– Sergio