Need to add elements of an array to a variable of JavaScript in JSP

275 Views Asked by At

I am creating an array for a list of markers of google map. The code works for one forEach loop but I need to add elements of a new array to the list as well.

My current code shows following error message on var of result2.

  Syntax error on token "var", ;  expected

Code for one array

var results = [
        <c:forEach var="cus" items="${customer}" varStatus="loop">[
            "${cus.value.name}", "${cus.value.latitude}",
            "${cus.value.longitude}", "${loop.index}",
            "${cus.value.id}"], </c:forEach> ];

Code for two arrays

var results = "[" +
                <c:forEach var="cus" items="${customer}" varStatus="loop">[
                        "${cus.value.name}", "${cus.value.latitude}",
                        "${cus.value.longitude}", "${loop.index}",
                        "${cus.value.id}"], </c:forEach> 

var results2 = results + <c:forEach var="staff" items="${staff}" varStatus="loop"> 
        + "[" +
                  "${staff.value.name}", "${staff.value.latitude}",
                  "${staff.value.longitude}", "${loop.index}",
                  "${staff.value.id}"], </c:forEach> 
        +"]";
1

There are 1 best solutions below

0
On BEST ANSWER

First of all, in your code for two arrays you don't want to have square brackets enclosed in the quotation marks. This will make your whole arrays result and result2 to be a Strings.
Second, closing bracket is missing for results, opening bracket is missing for results2.
Third, you cannot just + the arrays in JavaScript. There's a concat() method for that.

Try this:

var results = [
    <c:forEach var="cus" items="${customer}" varStatus="loop">
    [
        "${cus.value.name}",
        "${cus.value.latitude}",
        "${cus.value.longitude}",
        "${loop.index}",
        "${cus.value.id}"
    ],</c:forEach>
];

var results2 = results.concat([
    <c:forEach var="staff" items="${staff}" varStatus="loop">
    [
        "${staff.value.name}",
        "${staff.value.latitude}",
        "${staff.value.longitude}",
        "${loop.index}",
        "${staff.value.id}"
    ],</c:forEach>
]);