Skip to content

Instantly share code, notes, and snippets.

@luisenriquecorona
Created May 21, 2020 01:28
Show Gist options
  • Save luisenriquecorona/d4b087c0f0f91a9c71dd77f6f34388c0 to your computer and use it in GitHub Desktop.
Save luisenriquecorona/d4b087c0f0f91a9c71dd77f6f34388c0 to your computer and use it in GitHub Desktop.
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 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;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment