DekGenius.com
[ Team LiB ] Previous Section Next Section

3.13 Converting Arrays and Custom Objects to Strings

NN 4, IE 4

3.13.1 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.

3.13.2 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);

3.13.3 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) + "}";
    }
    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 += "'" + escape(val) + "',";
                    break;
                default:
                    output += val + ",";
            }
        }
        output = output.substring(0, output.length-1) + "]";
    }
    return output;
}
   
function string2Object(string) {
    eval("var result = " + string);
    return result;
}
   
function string2Array(string) {
    eval("var result = " + string);
    return result;
}

The first two functions of the library perform the conversion to strings. The first, object2String( ), works through the properties of a custom object, and assembles a string in the same format used to generate the object in the curly-braced shortcut syntax. The sole parameter to the function is a reference to the custom object you wish to convert. The returned value is a string, including the curly braces surrounding the text.

To demonstrate the effect of object2String( ), start with a simple object constructor:

function coworker(name, age, dept) {
    this.name = name;
    this.age = age;
    this.department = dept;
}

Create an instance of the object:

var kevin = new coworker("Kevin", 28, "Accounts Payable");

Convert the object to a string via the object2String( ) library function:

var objStr = object2String(kevin);

The value of objStr becomes the following string:

{name:'Kevin',age:28,department:'Accounts%20Payable'}

In the second library function, array2String( ), an array passed as the parameter is converted to its square bracket-encased shortcut string equivalent. Each function relies on the other at times. For example, if you are converting an object to a string, and one of its properties is an array, the array portion is passed through array2String( ) to get the desired format for that segment of the full string. Conversely, converting an array of objects requires calls to object2String( ) to format the object portions.

To reconstruct the object or array data type from the string, use one of the final two functions that applies to the outermost construction of the string. The two functions perform the same operation, but the names are provided for each conversion type to improve readability of the code that invokes them. Despite warnings elsewhere in this book about performance degradation of the eval( ) function, its use is necessary here.

Let the type of the outermost data structure govern which of the two convert-to-string functions you use. Even though your custom objects may be the most important part of your script data structure conceptually, they may be found within an array of those objects, as shown in Recipe 3.8. In this case, convert the entire array of objects to a single string by invoking array2String( ), and let it handle the object conversion along the way.

3.13.4 See Also

Recipe 3.1 and Recipe 3.8 to see the shortcut array and object creation syntax emulated here in string form; Recipe 4.8 for a discussion about the eval( ) function; Recipe 10.6 for an example of this library being used to pass objects between pages via URLs.

    [ Team LiB ] Previous Section Next Section