从JSON对象D3JS中获取最大值

Get max value from JSON objects D3JS

本文关键字:获取 最大值 D3JS JSON 对象      更新时间:2023-09-26

我有一个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
}

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

我所做的是:

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对象,而我想要的是nodes对象的变量Year的最大值。

我做错了什么?我该怎么补救呢?

谢谢!

你只需要一行

console.log(d3.max(graph.nodes, function(d) {return d.Year;} ));
工作小提琴

你只需要graph.nodes

yearmax

完整的示例

d3.json("swatwads.json", function(error, graph) {
  console.log(d3.max(graph.nodes, function(d) {return d.Year;} ));
  });

这是你想要的吗?

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