Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert scala list to javascript array?

Is there a simpler way of doing this?

 $(document).ready(function () {
        var jsArray = []
        @if(scalaList != null) {
            @for(id <- scalaList) {
            jsArray.push('@id');
           }
        }
    ...
    }
like image 634
Markku Avatar asked Mar 20 '13 10:03

Markku


3 Answers

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>
like image 86
Ryan Avatar answered Nov 06 '22 15:11

Ryan


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

like image 36
Martin Antczak Avatar answered Nov 06 '22 16:11

Martin Antczak


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(",")];
    ...
}
like image 2
korefn Avatar answered Nov 06 '22 16:11

korefn