How can I display any Javascript object as a string?

Asked

Viewed 2,621 times

3

If I have any object like new MeuObjeto(), and I want to string all its internal properties. 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 shown on alert() something like { prop1 = "Olá, Mundo!", prop2 = "Hahahaha", etc... }

3 answers

5

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 protection for circular references with

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

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

Works for your example, in more complex cases you may need to be tuned.

jsFiddle: https://jsfiddle.net/uL3mt94n/

  • That way you modify the object, that’s it?

  • @Not sergiocabral. I create a temporary variable _obj and I don’t touch anything obj.

4


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 = { };

  • There is no way to move the vector, it is better to do manual, the case vector system has pattern. Understand about "Array and Matrix Structure (Programming)" and tbm see about POO (Object-Oriented Programming)

2

To print an Object, you can serialize it first using the JSON.strigify, but this can become a headache if you have some circular reference in your object.

And since there is no normalization of how to deal with them in the object, then each library deals with it in a different way, for example the Json.NET - Newtonsoft in C# read in a way, already in JavaScript the implementation of JSON made by Douglas Crockford another’s deal.

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

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

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 might notice that the Snippet of StackOverFlow already uses a different approach to solve the circular reference problem.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.