将字符串作为对象添加到现有对象

时间:2013-02-18 16:24:15

标签: javascript jquery json charts

我正在构建一个动态的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对象中以使其完整。如果我$.parseJSON data对象,它会给我一个无效的对象对象。如何解析data对象以获取我需要的格式(使其与我给出的示例代码匹配)?

2 个答案:

答案 0 :(得分:3)

您可以通过将数据属性分配给来动态添加它:

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);

答案 1 :(得分: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;