1

我正在构建一个动态xChart。我传递的动态数据是一个预先构建的字符串,可以通过 js 转换为对象:

{"data": [{"x":"car insurance companies","y":1417},
          {"x":"insurance companies","y":17201},
          {"x":"auto insurance companies","y":892},
          {"x":"car insurance quote","y":3280},
          {"x":"auto insurance quote","y":988}]}

这是 xCharts 需要的参数代码示例片段:

var data = {
  "xScale": "ordinal",
  "yScale": "linear",
  "main": [
    {
      "className": ".pizza",
      "data": [
        {
          "x": "Pepperoni",
          "y": 4
        },
        {
          "x": "Cheese",
          "y": 8
        }
      ]
    }
  ]
};

这是我的一组参数:

var vars = {
    "xScale": "ordinal",
    "yScale": "linear",
    "type": "bar",
    "main": [
    {
        "className": ".topsy-results"
    }
    ]
};

我需要将我data的对象添加到main我的参数列表中的对象中以使其完整。如果我$.parseJSONdata对象,它会给我一个不起作用的对象。如何解析data对象以获得我需要的格式(使其与我提供的示例代码匹配)?

4

2 回答 2

3

您可以通过将data属性分配给main来即时添加它:

var myData={"data": [{"x":"car insurance companies","y":1417},
          {"x":"insurance companies","y":17201},
          {"x":"auto insurance companies","y":892},
          {"x":"car insurance quote","y":3280},
          {"x":"auto insurance quote","y":988}]};
vars.main.data = myData.data;
console.log(vars);
于 2013-02-18T16:28:51.180 回答
3

使用$.extend并合并两者?

var prebuilt = {...}; //that pre-build data
var vars = {...}; // Your vanilla settings

var merged = $.extend({}, vars, {
  'main': prebuilt
});

我已经放置prebuilt到另一个对象中,所以嵌套在它被扩展时会起作用,但现在prebuilt应该显示在data对象merged内部。注意: $.extend如果您拥有的不仅仅是数据信息,或者如果data属性中已经存在现有片段并且您想要更新它们或添加新片段,则很有用)。

您也可以通过引用简单地分配它:

vars.main.data = prebuilt.data;
于 2013-02-18T16:29:22.943 回答