Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting a Java ArrayList of strings to a JavaScript array

In my Java code, I have an ArrayList of Strings. I'd like to put this data in a JavaScript variable on a JSP page I'm working on. My first thought was to include it directly, e.g.:

var myArray = <%= arrayList %>;

Unfortunately, when executed, myArray is a string in the format [a,b,c], not an actual JavaScript array. How do I get some data from a Java ArrayList to a JavaScript array?

like image 699
Jack Avatar asked Jul 03 '13 05:07

Jack


4 Answers

The JavaScript split() method returns an array, so it's a simple way to convert a Java ArrayList into a JavaScript array.

function toJavascript(){
    var array="<%=javaArrayList%>";
    array=array.replace("[", "");
    array=array.replace("]", "");
    return javaArray.split(",");
}
like image 103
Vivek Jain Avatar answered Oct 22 '22 16:10

Vivek Jain


Withoug a library:

Java:

public static String toJavascriptArray(String[] arr){
    StringBuffer sb = new StringBuffer();
    sb.append("[");
    for(int i=0; i<arr.length; i++){
        sb.append("\"").append(arr[i]).append("\"");
        if(i+1 < arr.length){
            sb.append(",");
        }
    }
    sb.append("]");
    return sb.toString();
}

JSP:

var myArray = <%= toJavascriptArray(arrayList) %>;
like image 13
Uooo Avatar answered Oct 22 '22 18:10

Uooo


When you use <%=arraylist%> it calls the toString() on list and prints [a,b,c]

And No,you cannot direclty convert From Java arrayList to javascript array ,Convert the Java ArrayList to JSON String, and use JSON.parse() to get Javascript object.

Have a look at Json objet and Json in java

like image 5
Suresh Atta Avatar answered Oct 22 '22 17:10

Suresh Atta


Do the following in your JSP page

<% List<String> strList = new ArrayList<String>();
strList.add("one");
strList.add("two");
strList.add("three"); %>

var jsArray = [<% for (int i = 0; i < strList.size(); i++) { %>"<%= strList.get(i) %>"<%= i + 1 < strList.size() ? ",":"" %><% } %>];

The output will be

var jsArray = ["one","two","three"];

If your List was empty it will output

var jsArray = [];
like image 2
aaronvargas Avatar answered Oct 22 '22 18:10

aaronvargas