尝试在数组中创建一个新的json对象foreach项

时间:2014-06-20 16:06:17

标签: javascript arrays json charts

我有这种结构的大型json文件,每个文件只有很多图表:

{ 
    "Name": "test", 
    "Charts": [
    {
        "chartName": "Idle Times",
        "disk": 0,
        "OpCode": "Read",
        "xAxis": [0,100,200,300,400,500],
        "yAxis": [337487,8565,11419,9704,7598]
    },
    {
        "chartName": "Idle Times",
        "disk": 0,
        "OpCode": "Read",
        "xAxis": [0,100,200,300,400,500],
        "yAxis": [337487,8565,11419,9704,7598]
    }]
}

问题是所有的图表数据,x-y数据都在数组中,而我使用的javascript图表工具需要json看起来像这样:

{"chartName":"Idle Times", "disk":0, "OpCode":"Read","xAxis":0, "yAxis":1234},
{"chartName":"Idle Times", "disk":0, "OpCode":"Read","xAxis":100, "yAxis":1234},
{"chartName":"Idle Times", "disk":0, "OpCode":"Read","xAxis":200, "yAxis":1234},
{"chartName":"Idle Times", "disk":0, "OpCode":"Read","xAxis":300, "yAxis":1234},
{"chartName":"Idle Times", "disk":0, "OpCode":"Read","xAxis":400, "yAxis":1234},
{"chartName":"Idle Times", "disk":0, "OpCode":"Read","xAxis":500, "yAxis":1234},
{"chartName":"Idle Times", "disk":0, "OpCode":"Read","xAxis":600, "yAxis":1234}

我的应用目前正在使用AngularJS,JSLINQ,D3JS和DimpleJS。如果有办法用这些工具实现这一目标是理想的。我也对另一个开源库开放,我只是希望我不必阅读整个json文件并用一堆复杂的for循环来恢复它基本上构建新的json手工逐行。

我还可以切换到另一个图表工具,如果有什么能像我现在一样读取json数据,DimpleJS非常容易使用,看起来非常清晰。

提前感谢您的帮助!

2 个答案:

答案 0 :(得分:3)

因此,如果我理解正确,您希望将每个xy坐标扩展为单独的点? 尝试这样的事情:

var source = { 
    "Name": "test", 
    "Charts": [
    {
        "chartName": "Idle Times",
        "disk": 0,
        "OpCode": "Read",
        "xAxis": [0,100,200,300,400,500],
        "yAxis": [337487,8565,11419,9704,7598]
    },
    {
        "chartName": "Idle Times",
        "disk": 0,
        "OpCode": "Read",
        "xAxis": [0,100,200,300,400,500],
        "yAxis": [337487,8565,11419,9704,7598]
    }]
};

var data = source.Charts.reduce(function(prev, now) {
  var target = [];
  for(var i = 0, len = now.yAxis.length; i < len; i++) {
    target.push({
      "chartName": now.chartName,
      "disk": now.disk,
      "OpCode": now.OpCode,
      "xAxis": now.xAxis[i],
      "yAxis": now.yAxis[i]
    })
  }
  return prev.concat(target)
}, [])

只要你有相同数量的分数,这就行了。

答案 1 :(得分:2)

您似乎需要按下输入以匹配图表库的预期格式。这是一个片段,展示了如何做到这一点。

对于给定的输入:

var obj = {
    "chartName": "Idle Times",
    "disk": 0,
    "OpCode": "Read",
    "xAxis": [0,100,200,300,400],
    "yAxis": [337487,8565,11419,9704,7598]
};

循环遍历xAxis值:

var results = [];
for (var i = 0; i < obj.xAxis.length; i++) {
  results.push({
    "chartName":obj.chartName, 
    "disk":obj.disk,
    "OpCode":obj.OpCode,
    "xAxis":obj.xAxis[i],
    "yAxis":obj.yAxis[i]
  });
}