objectsArraysString.js

function object2String(obj) { var val, output = ""; if (obj) { output += "{"; for (var i in obj) { val = obj[i]; switch (typeof val) { case ("object"): if (val[0]) { output += i + ":" + array2String(val) + ","; } else { output += i + ":" + object2String(val) + ","; } break; case ("string"): output += i + ":'" + encodeURI(val) + "',"; break; default: output += i + ":" + val + ","; } } output = output.substring(0, output.length-1) + "}"; } return output; } function array2String(array) { var output = ""; if (array) { output += "["; for (var i in array) { val = array[i]; switch (typeof val) { case ("object"): if (val[0]) { output += array2String(val) + ","; } else { output += object2String(val) + ","; } break; case ("string"): output += "'" + encodeURI(val) + "',"; break; default: output += val + ","; } } output = output.substring(0, output.length-1) + "]"; } return output; } function string2Object(string) { eval("var result = " + decodeURI(string)); return result; } function string2Array(string) { eval("var result = " + decodeURI(string)); return result; }
Use the objectsArraysStrings.js script library shown in the Discussion. To convert a custom object to string form, invoke the object2String( ) function, passing a refer- ence to the object as a parameter: var objAsString = object2String(myObj); To convert an array (including an array of custom objects) to string form, invoke the array2String( ) function, passing a reference to the array as a parameter: var arrAsString = array2String(myArray); To reconvert the strings to native data types, use the corresponding library function: var myArray = string2Array(arrayString); var myObj = string2Object(objString);

Be the first to comment

You can use [html][/html], [css][/css], [php][/php] and more to embed the code. Urls are automatically hyperlinked. Line breaks and paragraphs are automatically generated.