I have made maps in D3 and I have conditionally assigned colors on id's and properties before. In this case I am trying to color conditionally depending on the presence of a specific word in the name. For example: color blue all countries with the word "United" in their names, all other countries pink. In this case it would color "United States", "United Kingdom", and "United Arab Emirates" blue. I have tried indexOf and some and str.includes but it results in: Uncaught TypeError: Cannot read property 'includes' of undefined.
Here is the code: https://jsfiddle.net/databayou/retk2pu6/7/
svg.selectAll(".country")
.data(topojson.feature(nations, nations.objects.countries).features)
.enter().append("path")
.attr("class", function(d) { return "country " + d.name; })
.attr("fill",function(d){
var str = d.name;
if (str.includes("United")) { return "blue"}
else {return "pink";
}
})
.attr("d", path);
Change var str = d.name;
to var str = d.properties.name;
If you console.log d
, you will see that name
is inside of properties
.