Convert any value to an array

var $U = {

	/* 
	/* function that always returns an array for the input value
	 */
	toArray : function(input) {
		try {
			
			if (typeof input === "undefined" || input === null) {
				//return empty array
				return [];	
			}
			
			if (typeof input === "string") {
				//convert string to array (or empty array)
				return ( input.length > 0 ? [input] : [] );
			}
				
			if (typeof input === "java.util.Vector") {
				
				//Normally we would use toArray here, but this returns an Object array.
				//If you try to use that in a doc.replaceItemValue call, it fails.
				//sample code:
				//var v = getComponent("input1").getValue();		//returns a Vector if the component contains multiple values
				//v = $U.toArray(v)		//returns an array of Objects
				//doc.replaceItemValue("someOtherField", v);		//fails
				
				//the solution I used here is to create a JS array and copy the all the Vector's values
				var a = [];
				var it = input.iterator();
				while (it.hasNext() ) {
					a.push( it.next() );
				}
				return a;
			}
			
			if (typeof input.toArray !== "undefined") {
				return input.toArray();
			}
			
			if ( input.constructor === Array ) {
				//return input if it's already an array
				return input;
			} 
	
			//return input as an array
			return [ input ];
			
		} catch(e) {
			print("$U.toArray: " + e.toString());
		}
	}
}





Serverside JavaScript is inconsistent in the return value of several methods if that method can return a single value or multiple values.

For instance, If you use getComponent("input1").getValue() and input1 contains multiple values, it returns a Vector. If it contains just a single text value it returns a string. Other examples of functions that might return a single value or an array are @dbLookup, @dbColumn, @trim and @unique

To workaround this you can use this function that always returns an array (also if the input is already an array).

Usage examples:

var result = $U.toArray( @dbLookup(@dbName, "view", "key", "field") );
var result = $U.toArray( getComponent("input1").getValue() );

(note: I'm using the $U object for a set of utility functions)

JavaScript (Server)
Mark Leusink
December 2, 2011 7:09 AM
Rating
873

All code submitted to OpenNTF XSnippets, whether submitted as a "Snippet" or in the body of a Comment, is provided under the Apache License Version 2.0. See Terms of Use for full details.



No comments yetLogin first to comment...