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());
		}
	}
}
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...