J2js - Global

2JS script include allows you to convert java objects to JavaScript objects.

If the given value is a Java object that can be converted to an equivalent JavaScript object, that conversion is performed and the result is returned. Otherwise the original Java object is returned.

The j2js class is available to server-side scripts.

The specific conversion performed in the order they are checked.
  • Java String -> JavaScript string
  • Java Boolean -> JavaScript boolean
  • Java Integer -> JavaScript number
  • Java Long -> JavaScript number
  • Java Double -> JavaScript number
  • Java Byte -> JavaScript number
  • Java Float -> JavaScript number
  • Java Short -> JavaScript number
  • Java Character -> JavaScript number
  • Java array -> JavaScript Array with order preserved
  • Java List -> JavaScript Array with order preserved
  • Java Map -> JavaScript Object with the key/value pairs translated into property/value pairs
  • Java Set -> JavaScript Array in arbitrary order

Conversions are performed recursively on the elements of arrays, lists, or collections. For example, given a Java ArrayList of ArrayLists of Strings, this will return a JavaScript Array of Arrays of strings.

J2js - j2js(Object javaObject)

Convert a java object from system code to a JavaScript object.

Table 1. Parameters
Name Type Description
javaObject Object A Java object from system code such as a Packages call.
Table 2. Returns
Type Description
Object A JavaScript object if the parameter can be converted, otherwise it returns the Java object.

var tu = new TableUtils("cmdb_ci_win_server");
var classes = tu.getHierarchy();
//getHierarchy returns a Java ArrayList, which is not exactly like a JavaScript Array
//for example you cannot get length
gs.print("classes = " + classes);
gs.print("classes.length = " + classes.length);
 
//convert to a JavaScript Array
gs.include("j2js");
var jsClasses = j2js(classes);
gs.print("jsClasses = " + jsClasses);
gs.print("jsClasses.length = " + jsClasses.length);
Output:
classes = [cmdb_ci_win_server, cmdb_ci_server, cmdb_ci_computer, cmdb_ci_hardware, cmdb_ci]
classes.length = undefined
jsClasses = cmdb_ci_win_server,cmdb_ci_server,cmdb_ci_computer,cmdb_ci_hardware,cmdb_ci
jsClasses.length = 5