How can I display any JavaScript object as a string?

2

If I have any object like new MeuObjeto() , and I want to display all its internal properties as string. How can I do this?

When I use alert(new MeuObjeto()) the result is [object Object] . But I want the content of the object as text, string .

var MeuObjeto = function() {
    this.prop1 = "Olá, Mundo!";
    this.prop2 = "Hahahaha";
    this.recursivo = this;
    this.funcao = function() { return "retorno da função"; }
}
alert(new MeuObjeto());

In this case I want it to be displayed in alert() something like { prop1 = "Olá, Mundo!", prop2 = "Hahahaha", etc... }

    
asked by anonymous 03.08.2016 / 16:21

3 answers

3

You can write this function to convert any object to string .

See this JSFiddle sample function below

function ToString(obj) {
    clearTimeout(window.ToStringTimeout);

    var result;
    var ident = arguments.length >= 2 ? arguments[1] : undefined;

    if (obj == null) {
        result = String(obj);
    }

    if (!result) {
        window.ToStringRecursive = window.ToStringRecursive ? window.ToStringRecursive : [];
        if (ToStringRecursive.indexOf(obj) >= 0) {
            result = obj ? (typeof(obj) == "string" ? "\"" + obj + "\"" : obj.toString()) : obj;
        } else {
            ToStringRecursive.push(obj);
        }
        if (!result) {
            switch (typeof obj) {
                case "string":
                    result = '"' + obj + '"';
                    break;
                case "function":
                    result = obj.name || obj.toString();
                    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 = obj.toString();
                    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"; }
}

See that when a property is recursive it is not displayed again because it would loop endlessly.

    
03.08.2016 / 16:21
4

I think you can do it like this:

function stringify(algo) {
    function checktype(obj) {
        if (!obj || typeof obj == 'number' || typeof obj == 'string') return obj;
        if (typeof obj == 'function') return obj.toString();
        var _obj = Array.isArray(obj) ? [] : {};
        Object.keys(obj).forEach(function(key) {
            if (obj[key] == obj) _obj[key] = 'instance of itself';
            else _obj[key] = checktype(obj[key]);
        });
        return _obj;
    };
    return JSON.stringify(checktype(algo), '\t', 4);
};

I created a circular circle protection with

if (obj[key] == obj) _obj[key] = 'instance of itself';

Another option would be to limit the depth of the object.

It works for your example, in more complex cases it may need to be tuned.

jsFiddle: link

    
03.08.2016 / 17:13
1

To print an Object, you can serialize it first using JSON.strigify , but this may turn out to be a headache if you have some circular reference on your object.

And since there is no normalization of how to handle them in the object, then each library handles it differently, for example Json.NET - Newtonsoft in C # read in a way, already in JavaScript to the implementation of JSON done by Douglas Crockford read from another.

In general, they use the definition used by JSON Schema to mount a schema to JSON , but with some minor differences (and in this difference where the danger lives, and as a result it is hell to send this object via AJAX to whatever place).

Below is an example using the Douglas Crockford library to solve the problem of circular reference JSON.strigify to print it.

var MeuObjeto = function() {
    this.prop1 = "Olá, Mundo!";
    this.prop2 = "Hahahaha";
    this.recursivo = this;
    this.funcao = function() { return "retorno da função"; }
}

var obj = new MeuObjeto();

obj = JSON.decycle(obj);
console.log(JSON.stringify(obj));

obj = JSON.retrocycle(obj);
console.log(obj);
<script src="https://rawgit.com/douglascrockford/JSON-js/master/cycle.js"></script>

And finally, you may notice that Snippet of StackOverFlow already uses a different approach to solve the circular reference problem.

    
03.08.2016 / 18:36