Converting an object to a string

后端 未结 30 2408
北荒
北荒 2020-11-22 03:29

How can I convert a JavaScript object into a string?

Example:

var o = {a:1, b:2}
console.log(o)
console.log(\'Item: \' + o)

Output:

30条回答
  •  我寻月下人不归
    2020-11-22 04:27

    None of the solutions here worked for me. JSON.stringify seems to be what a lot of people say, but it cuts out functions and seems pretty broken for some objects and arrays I tried when testing it.

    I made my own solution which works in Chrome at least. Posting it here so anyone that looks this up on Google can find it.

    //Make an object a string that evaluates to an equivalent object
    //  Note that eval() seems tricky and sometimes you have to do
    //  something like eval("a = " + yourString), then use the value
    //  of a.
    //
    //  Also this leaves extra commas after everything, but JavaScript
    //  ignores them.
    function convertToText(obj) {
        //create an array that will later be joined into a string.
        var string = [];
    
        //is object
        //    Both arrays and objects seem to return "object"
        //    when typeof(obj) is applied to them. So instead
        //    I am checking to see if they have the property
        //    join, which normal objects don't have but
        //    arrays do.
        if (typeof(obj) == "object" && (obj.join == undefined)) {
            string.push("{");
            for (prop in obj) {
                string.push(prop, ": ", convertToText(obj[prop]), ",");
            };
            string.push("}");
    
        //is array
        } else if (typeof(obj) == "object" && !(obj.join == undefined)) {
            string.push("[")
            for(prop in obj) {
                string.push(convertToText(obj[prop]), ",");
            }
            string.push("]")
    
        //is function
        } else if (typeof(obj) == "function") {
            string.push(obj.toString())
    
        //all other values can be done with JSON.stringify
        } else {
            string.push(JSON.stringify(obj))
        }
    
        return string.join("")
    }
    

    EDIT: I know this code can be improved but just never got around to doing it. User andrey suggested an improvement here with the comment:

    Here is a little bit changed code, which can handle 'null' and 'undefined', and also do not add excessive commas.

    Use that at your own risk as I haven't verified it at all. Feel free to suggest any additional improvements as a comment.

提交回复
热议问题