【问题标题】:Get max value from JSON objects D3JS从 JSON 对象 D3JS 中获取最大值
【发布时间】:2015-05-18 09:52:38
【问题描述】:

我有一个这样的 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 的最大值。

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

谢谢!

【问题讨论】:

  • 为什么要对对象graph 进行字符串化,然后使用解析将字符串转回对象?这似乎是不必要的。如果它已经是一个对象,为什么将其转换为 json 以将其转换回 obj ??? graphRec=JSON.parse(JSON.stringify(graph)); 或者你想破坏引用?
  • graphdata ==graph == graphRec 所有这三个对象似乎毫无意义。只需使用图表!
  • @Liam 似乎是合法的,我看到了一个例子,它说在检索数据时这是一种很好的做法,但在我的情况下却不是。我删除了那条线,但我仍然得到相同的结果

标签: javascript json d3.js


【解决方案1】:

你只是想要这条线

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

Working fiddle

所以您只需要来自graph.nodesyearmax

完整示例

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

【讨论】:

    【解决方案2】:

    这是你想要的吗?

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

    【讨论】:

    • 如果你自己动手,这有点违背了使用 d3 的目的?
    猜你喜欢
    • 2020-09-28
    • 2011-02-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-05-08
    • 1970-01-01
    • 2016-01-29
    • 1970-01-01
    相关资源
    最近更新 更多