我正在构建一个动态的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
对象以获取我需要的格式(使其与我给出的示例代码匹配)?
答案 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;