繁体   English   中英

如何从该数组中的值获取特定的JSON数组

[英]How to get the specific JSON array from a value in that array

我是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的索引并使用它来查找population数组中的种群。 但我需要根据Id找到。 有人可以告诉我怎样才能得到这个。

首先,因为你是JSON的新手,一个小的术语修正来帮助你:JSON是一个字符串而不是一个对象,因此它是J ava S cript O bject N otation的缩写。 你所拥有的通俗地称为POJO或P lain O ld J avascript O bject。 它们是不同的。

现在提出你的问题。 你有两种方法:

  1. 您可以使用poly-fill来制作即将推出的ECMA 6阵列方法,并为将来的答案提供证据
  2. 或者您可以使用ECMA 5功能推出自己的解决方案

第一个解决方案是使用文档中提供的poly-fill进行find

var countryData = data.find(function(element, index, array) {
  return element.Id === 'SWE';
});

countryData.Population // 9592552

第二种方法基本上是以您选择的任何方式重新创建聚合填充,如果您选择该选项,我会将其留给您作为练习来学习。

 if (!Array.prototype.find) { Array.prototype.find = function(predicate) { if (this == null) { throw new TypeError('Array.prototype.find called on null or undefined'); } if (typeof predicate !== 'function') { throw new TypeError('predicate must be a function'); } var list = Object(this); var length = list.length >>> 0; var thisArg = arguments[1]; var value; for (var i = 0; i < length; i++) { value = list[i]; if (predicate.call(thisArg, value, i, list)) { return value; } } return undefined; }; } var data = [{ "Id": "SWE", "Country": "Sweden", "Population": 9592552 }, { "Id": "NOR", "Country": "Norway", "Population": 5084190 }]; function display(e) { console.log("E", e); var countryData = data.find(function(element, index, array) { return element.Id === e; }); console.log(countryData.Population); } display('SWE'); 

只需循环直到你看到正确的ID。

for (var i in data) {
    if (data[i].Id == 'SWE') console.log(data[i]['Population']);
}

您还可以使用while循环或常规for循环。 这里的每一个i在数据“键”被测试,因此每片数据是data[i]

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM