O'Reilly logo

JavaScript & DHTML Cookbook by Danny Goodman

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Converting Arrays and Custom Objects to Strings

NN 4, IE 4

Problem

You want to convert the details of an array or a custom object into string form for conveyance as a URL search string or preservation in a cookie, and then be able to reconstruct the array or object data types from the string when needed later.

Solution

Use the objectsArraysStrings.js script library shown in the Discussion. To convert a custom object to string form, invoke the object2String( ) function, passing a reference 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);

Discussion

Example 3-1 shows the code for the objectsArraysString.js library.

Example 3-1. objectsArraysString.js conversion library

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 + ":'" + escape(val) + "',"; break; default: output += i + ":" + val + ","; } } output = output.substring(0, output.length-1) + "}"; ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required