user3821345 February 2016

D3 How to filter menu based on nested data

I have the following plunk https://plnkr.co/edit/gDbUE99nNNMtYp9IpR1d?p=info and am struggling to get my dropdown menu working with nested data. Ive generated a menu from a first level nest ('starting point'), which shows a list of nationalities that is generated from the second level nest ('Nat'). I want to use the menu to load the different 'Nat' assosicated with each 'starting point'.

Previously I created my menu like this, but it doesn't seem to be working with 'nested_data'. Is d3.filter() wrong for this?

list.on('change', function() {
      var selected = d3.select(this).select("select").property("value")
      var cd = nested_data.filter(function(d) {
           return (selected == d.key)
      });
   updateNested_data(cd)
  });

...

var filter = nested_data.filter(function(d) {
       return ("Berkner Island" == d.key)
   });
  updateNested_data(filter)

I'm also having a problem with exit() in my update function, I think because I'm binding my data too early? But for this question I'd like to focus on how to get the menu working.

Full code

d3.csv("data.csv", function(CSV) {

  var nested_data = d3.nest()
      .key(function(d) {
      return d['starting point'];
      })
      .key(function(d) {
      return d.Nat;
      })
      .entries(CSV);

  // CREATE DROPDOWN
  var list = d3.select("#opts")

  list.append("select").selectAll("option")
      .data(nested_data)
      .enter().append("option")
      .attr("value", function(d) {
         return d.key;
      })
      .text(function(d) {
         return d.key;
      });

  // MENU
  list.on('change', function() {
      var selected = d3.select(this).select("select").property("value")
      var cd = nested_data.filter(function(d) {
           return (selected == d.key)
      });
   updateNested_data(cd)
  });

  // CONFIG
  var canvas = d3.sel        

Answers


Cyril February 2016

There is no problem anywhere except the way you entering and exiting:

function updateNested_data(cd) {
      //set the data to the selection
      var country = canvas.selectAll(".country").data(cd.values)

      var countryEnter = country

          .enter().append('div')
          .attr('class', 'country')

      countryEnter
            .append("p")
            .attr('class', 'label')
            .style('font-weight', 'bold')
            .text(function(d) {
                return d.key;
            })
      //exit on selection
      country.exit().remove();

  };

working code here

Post Status

Asked in February 2016
Viewed 2,604 times
Voted 4
Answered 1 times

Search




Leave an answer