How to convert Map to Json object in Scala.js?

不打扰是莪最后的温柔 提交于 2019-12-12 01:58:09

问题


I'm trying to write a facade for C3.js line chart.

The Javascript code I'm trying to generate is

var chart = c3.generate({
    data: {
        json: {
            "data1": [49.1, 20, 50, 40, 60, 50],
            "data2": [200.3, 130, 90, 240, 130, 220],
            "data3": [300.88, 200, 160, 400, 250, 250]
        }
    }
});

This is how I'm invoking the facade I've written

C3Chart.generate(scope.props.data)

The problem is that I'm not able to convert the apply method in C3MyChartDataset class to return a json object to emit this object

 json: {
        "data1": [49.1, 20, 50, 40, 60, 50],
        "data2": [200.3, 130, 90, 240, 130, 220],
        "data3": [300.88, 200, 160, 400, 250, 250]
    }

How do I convert a Map to a JSON object in Scala-js ?

@JSName("c3")
object C3Chart extends js.Object {
  def generate(data: MyChartData): js.Dynamic = js.native
}

trait C3MyChartDataset extends js.Object {
  def json: js.Object = js.native
}

object C3MyChartDataset {
  def apply(data: Map[String, Array[Double]]): C3MyChartDataset = {
    js.Dynamic.literal(
      json = data //I need to convert this into an object
    ).asInstanceOf[C3MyChartDataset]
  }
}

trait MyChartData extends js.Object {
  def data: js.Object = js.native
}

object MyChartData {
  def apply(datasets: C3MyChartDataset): MyChartData = {
    js.Dynamic.literal(
      data = datasets
    ).asInstanceOf[MyChartData]
  }
}

Update: I've tried converting it to Dictionary object by using toJSDictionary. (json = data.toJSDictionary). But this still does not generate the chart. The resulting Javascript object using toJSDictionary is

data: Object
    json: Object
        Data1: $TypeData.initArray.ArrayClass
           u: Array[6]
           0: 30.1
           1: 200.1
           2: 100.1
           3: 400.1
           4: 150.1
           5: 250.1

回答1:


The type of your json object is basically a dictionary whose values are arrays of numbers. Translated to a Scala.js type, that means

js.Dictionary[js.Array[Double]]

You can convert your data of type Map[String, Array[Double]] to that type with

data.mapValues(_.toJSArray).toJSDictionary



回答2:


Assuming my question above is correct, you probably want js.Dictionary -- this is the usual Scala.js representation of a normal JavaScript object that you think of as name/value pairs. Note that it has a (String, A)* constructor that is pretty easy to convert from Map.



来源:https://stackoverflow.com/questions/31655070/how-to-convert-map-to-json-object-in-scala-js

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!