简体   繁体   中英

How to merge data from D3.js Topojson to defined set to set class

So I'm using the Topojson functionality of D3.js to create an svg world map. I've managed to figure out the scale and everything perfectly so far despite being relatively new to d3. The issue I'm having is attempting to merge or filter the data from the topojson file with some sets that I have defined. I'm going to leave out the functions used for projection. Here's what I have so far:

var svg = d3.select("#map svg");
var regions = [
    {
        region: 'low',
        set: d3.set([ "USA", "CAN" ])
    },
    {
        region: 'med',
        set: d3.set([ "AUS" ])
    },
    {
        region: 'high',
        set: d3.set([ "RUS" ])
    }
];
d3.json("site/js/topo.json", function(error, topology) {
    // INDIVIDUAL COUNTRIES
    svg.selectAll("path")
        .data(topojson.feature(topology, topology.objects.worldByIso).features)
        .enter()
        .append("path")
        .attr("data-iso", function(d){ 
            return d.properties.iso;
        })
        .attr("d", path);
});

I'm able to return the d.properties.iso value from the topojson file to a data attribute, but what I'd really like to do is check that iso property against the 'regions' array to instead return the region (low, med, or high) if it matches the set.

Ideally the solution wouldn't need to loop through 'regions' each time to check so it can be processed quickly. Hopefully this all makes sense, I'm writing this as I run out the door from overtime!

Array.reduce

I think you want Array.reduce() . This will let you collapse an array to a single value. I changed your d3.sets to simple arrays so I could use the contains() method but a quick glance at the d3 documentation looks like their sets have has() instead.

 var regions = [{ region: 'low', set: ["USA", "CAN"] }, { region: 'med', set: ["AUS"] }, { region: 'high', set: ["RUS"] } ]; let getRegion = r => regions.reduce((a, c) => c.set.includes(r) ? c.region : a, null); console.log(getRegion('AUS')); console.log(getRegion('USA')); console.log(getRegion('EUR')); 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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