【发布时间】:2015-04-11 04:27:00
【问题描述】:
我是 d3.js 和 JSON 的新手。我通过做一些小的可视化来学习。现在,我正在尝试加载 JSON 数据并根据国家/地区代码可视化详细信息。
我的 JSON 数据是这样的:
[
{
"Id":"SWE",
"Country":"Sweden",
"Population":9592552
},
{
"Id":"NOR",
"Country":"Norway",
"Population":5084190
},
.
.
.
]
我有世界国家地理 JSON,我可以成功地对其进行可视化,还可以突出显示所选国家并获取所选国家的 ID。现在我需要获取详细信息(基于我从选择中获得的 id 的那个国家的人口和国家名称)。有人可以告诉我如何从 JSON 数组中获取值。
我试过了
population = data.map( function(d) { return d["Population"] });
但是这个给了我整个人口作为一个数组。如何根据 Id 获取 SWE 的人口?
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<script src="http://d3js.org/d3.v3.min.js"></script>
<style>
</style>
<script type="text/javascript">
var data;
function draw(geo_data) {
"use strict";
var margin = 75,
width = 1400 - margin,
height = 600 - margin;
var svg = d3.select("body")
.append("svg")
.attr("width", width + margin)
.attr("height", height + margin)
.append('g')
.attr('class', 'map');
var projection = d3.geo.mercator()
.scale(150)
.translate( [width / 2, height / 1.5]);
var path = d3.geo.path().projection(projection);
var map = svg.selectAll('path')
.data(geo_data.features)
.enter()
.append('path')
.attr('d', path)
.style('fill', 'lightBlue')
.style('stroke', 'black')
.attr("id", function(d) {
return d.id; })
.on("click", function(d, i) {
d3.select(".selected").classed("selected", false).style('fill', 'lightBlue');
d3.select(this).classed("selected", true).style('fill', 'red');
console.log(d.id)
display(d.id)
})
.style('stroke-width', 0.5);
};
d3.json("data/wrangledData_overallScore.json", function (error, json) {
if (error) return console.warn(error);
data = json;
console.log("JSON", data);
});
function display(e){
var population = data.map( function(d) { return d["Population"] });
console.log(population)
}
</script>
</head>
<body>
<script type="text/javascript">
/*
Use D3 to load the GeoJSON file
*/
d3.json("data/world-countries.json", draw);
</script>
</body>
</html>
我可以获取 id 的索引并将其用于在人口数组中查找人口。但是我需要根据Id查找。有人可以告诉我我怎么能得到这个。
【问题讨论】:
-
我对类似问题的回答可能会有所帮助stackoverflow.com/a/32791194/1815624
标签: javascript json d3.js