如何从该数组中的值获取特定的JSON数组 [英] How to get the specific JSON array from a value in that array

查看:237
本文介绍了如何从该数组中的值获取特定的JSON数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是d3.js和JSON的新手。我通过做一些小的小的可视化学习。现在,我试图加载JSON数据,并基于国家代码可视化的细节。

I am new to d3.js and JSON. I am learning by doing some small small visualizations. Now, I am trying to load a JSON data and visualize the details based on the country code.

我的JSON资料如下:

My JSON data is like :

[
  {
    "Id":"SWE",
    "Country":"Sweden",
    "Population":9592552
  },
  {
    "Id":"NOR",
    "Country":"Norway",
    "Population":5084190
  },
.
.
.
]

我有世界各国geo JSON,我可以成功地以突出显示所选国家/地区并获取所选国家/地区的ID。现在我需要得到的细节(国家的人口和国家名称,基于我从选择的ID)。可以有人告诉我如何从JSON数组获取值。

I have world countries geo JSON which I can able to visualize successfully and also able to highlight the selected country and get the selected country's id. Now I need to get the details (population and country name of that country based on the id I got from selection). Can Some one tell how can I get the values from the JSON array.

我试过像

 population = data.map( function(d) { return d["Population"] });

但这一个给我整个人口作为一个数组。如何根据Id获取SWE的人口?

but this one gives me entire populations as an array. How do I get population for SWE based on Id ?

<!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。有人可以告诉我怎么能得到这个。

I can get the index of the id and use that for finding population in the population array. But I need to find based on Id. Can Some one please tell me how can I get this.

推荐答案

首先,因为你是JSON的新手,有些术语修正可以帮助你:JSON是一个字符串,对象因此是 J ava S 脚本 O 对象 N 标签的缩写。您所拥有的内容通常称为POJO或 P 提供 O ld J avascript O 对象。他们是不同的。

First, since you are new to JSON, a little terminology correction to help you out: JSON is a string and not an object hence it's abbreviation of JavaScript Object Notation. What you have is colloquially referred to as a POJO or Plain Old Javascript Object. They are different.

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

Now for your question. You have two approaches:


  1. 您可以为即将到来的ECMA 6阵列方法使用多重填充,
  2. 或者您可以使用ECMA 5功能卷自己的解决方案

第一个解决方案是使用poly -fill在 <$ c $的文档中提供c> find

The first solution would be to use the poly-fill provided in the documentation for find:

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

countryData.Population // 9592552

第二种方法基本上是重新创建如果你选择这个选项,我将把它留给你作为一个练习来学习。

The second method is basically recreating the poly-fill in a whatever manner you choose and if you choose that option I'll leave that up to you as an exercise to learn from.

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');

这篇关于如何从该数组中的值获取特定的JSON数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆