user4565448
user4565448

Reputation:

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

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.

My JSON data is like :

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

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.

I tried like

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

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>

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.

Upvotes: 3

Views: 4787

Answers (2)

Jason Cust
Jason Cust

Reputation: 10899

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. You can use a poly-fill for an upcoming ECMA 6 array method and future proof your answer
  2. Or you can roll your own solution using ECMA 5 functionality

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

Upvotes: 4

bjb568
bjb568

Reputation: 11498

Just loop thru them until you see the right id.

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

You could also use a while loop or regular for loop. Here every i "key" in data is tested, so each piece of data is data[i].

Upvotes: 1

Related Questions