Skip to main content
AI Assist is now on Stack Overflow. Start a chat to get instant answers from across the network. Sign up to save and share your chats.
added the suggested edit by andrey
Source Link
Houshalter
  • 2.8k
  • 1
  • 21
  • 21

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.

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.

Source Link
Houshalter
  • 2.8k
  • 1
  • 21
  • 21

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("") }