Converting an object to a string

后端 未结 30 2294
北荒
北荒 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:28

    If you only care about strings, objects, and arrays:

    function objectToString (obj) {
            var str = '';
            var i=0;
            for (var key in obj) {
                if (obj.hasOwnProperty(key)) {
                    if(typeof obj[key] == 'object')
                    {
                        if(obj[key] instanceof Array)
                        {
                            str+= key + ' : [ ';
                            for(var j=0;j 0 ? ',' : '') + '}';
                                }
                                else
                                {
                                    str += '\'' + obj[key][j] + '\'' + (j > 0 ? ',' : ''); //non objects would be represented as strings
                                }
                            }
                            str+= ']' + (i > 0 ? ',' : '')
                        }
                        else
                        {
                            str += key + ' : { ' + objectToString(obj[key]) + '} ' + (i > 0 ? ',' : '');
                        }
                    }
                    else {
                        str +=key + ':\'' + obj[key] + '\'' + (i > 0 ? ',' : '');
                    }
                    i++;
                }
            }
            return str;
        }
    

提交回复
热议问题