从JSON对象D3JS获取最大值

时间:2015-05-18 09:52:39

标签: javascript json d3.js

我有一个像这样的JSON文件:

{  
   "directed":false,
   "graph":[  
      [  
         "node_default",
         {  

         }
      ],
      [  
         "name",
         "()_with_int_labels"
      ],
      [  
         "edge_default",
         {  

         }
      ]
   ],
   "nodes":[  
      {  
         "id":0,
         "Year":1996,
         "Venue":"SWAT",
         "cYear":1996,
         "label":"The randomized complexity of maintaining the minimum"
      },
      {  
         "id":1,
         "Year":1998,
         "Venue":"SWAT",
         "cYear":1998,
         "label":"Probabilistic data structures for priority queues"
      }
   ],
   "links":[  
      {  
         "Edge Id":"12640",
         "target":65,
         "source":0,
         "Year":2011
      },
      {  
         "Edge Id":"12714",
         "target":50,
         "source":0,
         "Year":1996
      }
   ],
   "multigraph":false
}

我希望从Year获取变量nodes的最大值,并首先在控制台日志中显示它,然后将其用作变量以进行进一步处理。

我做的是:

d3.json("swatwads.json", function(error, graph) {
  graphdata=graph;
  graphRec=JSON.parse(JSON.stringify(graph)); //Add this line

  // Node and Link habitual defitions

  console.log(d3.max(d3.values(graph.nodes, function(d) {return d.Year;} )));

  });

当我运行代码时,它会检索整个第一个nodes对象,而我想要的是Year对象的变量nodes的最大值。

我做错了什么?我该如何解决?

谢谢!

2 个答案:

答案 0 :(得分:4)

你只想要一行

OUTPUT

Working fiddle

因此,您只需要console.log(d3.max(graph.nodes, function(d) {return d.Year;} )); 的{​​{1}}值max

完整示例

year

答案 1 :(得分:1)

这样做你想要的吗?

d3.json("swatwads.json", function(error, graph) {
  var nodes = graph.nodes
  var max = 0
  for (var ii=0, node; node=nodes[ii]; ii++){
    if (node.Year > max) {
      max = node.Year
    }
  }
  console.log(max)
}