How to convert scala list to javascript array?
Asked Answered
S

4

9

Is there a simpler way of doing this?

 $(document).ready(function () {
        var jsArray = []
        @if(scalaList != null) {
            @for(id <- scalaList) {
            jsArray.push('@id');
           }
        }
    ...
    }
Shanika answered 20/3, 2013 at 10:15 Comment(0)
D
9

It's as simple as the following:

import play.api.libs.json.Json

val jsArr: JsValue = Json.toJson(scalaList)

You can also do that within a template:

@(list: List[Any])

@import play.api.libs.json.Json

<script type="text/javascript">
    $(document).ready(function () {
        var jsArr = @Json.toJson(list);
        console.log(jsArr);
    });
</script>
Diplopia answered 20/3, 2013 at 17:27 Comment(2)
I get the output like this: var jsArr = [&quot;xxxx&quot;,&quot;yyyy&quot;]; instead of actual quotes.Seaborne
It should be @Html(Json.stringify(Json.toJson(list)))Rebound
I
3

You can use mkString for this.

  $(document).ready(function () {
    var jsArray = @if(scalaList != null) {
      [ @scalaList.mkString(",") ]} 
    else {[]};
  }

You should omit this if statement in view. Instead of this, check null in controller and put empty list to view, so this code can be more simpler in view

 $(document).ready(function () {
    var jsArray = [ @scalaList.mkString(",") ];
 }

You don't need this quotes ' ' around id. In javascript 1 == '1' is true

Izaak answered 20/3, 2013 at 10:57 Comment(0)
M
2

Have you tried something like:

var jsArray = new Array(@scalaList.map(x => "\"" + x + "\"").mkString(","));

or you can use a literal like

var jaArray = [    var jsArray = [@scalaList.map(x => "\"" + x + "\"").mkString(",")];

Also the if check is not required. For comprehensions are smart like that

$(document).ready(function () {
    var jsArray = [@scalaList.map(x => "\"" + x + "\"").mkString(",")];
    ...
}
Muster answered 20/3, 2013 at 10:56 Comment(0)
M
2

I think every answer are good but still not safe because every answers don't care about value which including ' or ". Fortunately play framework support json, so you should use json to convert to javascript array.

 @(json: String)
 <html>
 <head>
 </head>
 <body>
 <script>
 var json = @Html(json);
 var list = json.list;
 </script>
 </body>
 </html>
 package controllers

 import play.api._
 import play.api.libs.json._
 import play.api.mvc._

 object Application extends Controller {

   def index = Action {
     val list = List( "hoge\"hoge", "moge'mo\"ge" )
     val json = Json.stringify( Json.obj( 
       "list" -> JsArray( list.map( JsString(_) ) )
     ))
     Ok(views.html.index(json))
   }

 }
Maffei answered 20/3, 2013 at 12:54 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.