Surabhi
Surabhi

Reputation: 3896

Looping 2D ArrayList in javascript

Below data is returned from Servlet to JSP.

List< List < String > > formData = new ArrayList< List< String > >();

formData has [[A, D], [, E], [B], [], [], [C]]

I am unable to loop through above list using javascript in jsp.

I tried assigning formdata to a variable and accessed it using index as below

In JSP:

var myData = "${formData}";

var i=0;

var j=0;

alert(myData[i][j]) 

alert shows the value as undefined.

Please let me know how to loop through formData list.

Upvotes: 0

Views: 1974

Answers (3)

Giovanni Filardo
Giovanni Filardo

Reputation: 1022

I don't think that printing the toString of a bidiminsional collection of strings from jsp in the javascript source is a good idea. That's one of the things transport/representational languages have been created for. For this reason, I would suggest to print the JSON representation of that bidimensional collection. What you need in the JavaScript source code, a bidimensional array of String is:

[["A", "D"], [, "E"], ["B"], [], [], ["C"]]

Notice the double quotes, those are important, without those, the generated javascript array is a bidimensional array of variables (A, D, E, B, C).

For example, using Gson (google json library), in Java I would create formData like this:

Gson gson = new Gson();
String toPrintInTheJSP = gson.toJson(<your Java bidimensional collection of strings here>);

In the JSP I would output:

var myData = ${formData}; //without the double quotes
var i=0, j=0;
alert(myData[i][j]) 

If you need to cycle through the collection in JSP (that means while generating the markup (I quote, "I tried assigning formdata to a variable and accessed it using index as below In JSP: [...]") ), there are different methods to do that, for example a scriptlet or JSTL.

I'm not really sure about what you have to do, the terminology you used in your question is a little bit imprecise. I think you need to cycle in JavaScript on a bidimensional array written by a JSP.

If you have to cycle through the array in JavaScript, you need a nested loop, like this:

    var myData = [["A", "D"], [, "E"], ["B"], [], [], ["C"]];
    for (var i = 0; i < myData.length; i++){
        for(var j = 0; j < myData[i].length; j++){
            alert(myData[i][j]);
        }
    }

Upvotes: 1

Florian Margaine
Florian Margaine

Reputation: 60737

var myData = "${formData}";

Transforms to:

var myData = "[[A, D], [, E], [B], [], [], [C]]";

In javascript, to create an array, you have to use:

var myData = [[A, D], [, E], [B], [], [], [C]];

Upvotes: 0

Sirko
Sirko

Reputation: 74046

Remove the brackets around ${formdata}in your JSP:

var myData = ${formData};

var i=0;

var j=0;

alert( myData[i][j] ) ;

Your were assigning a string to myData. To loop through the array, you either need to parse that string using JSON.parse() or assign it as an array directly as shown above.

Upvotes: 0

Related Questions