Problem:
I have two objects in a d3 construct:
const visitors = [
{
name: "polygon 1",
total: 342,
color: "red"
},
{
name: "polygon 2",
total: 342,
color: "blue"
},
{
name: "polygon 3",
total: 342,
color: "green"
}
]
const polys = [{
name: "polygon 1",
points:[
{"x":-25, "y":48},
{"x":3,"y":48},
{"x":3,"y":40},
{"x":-25,"y":40},
{"x":-25,"y":48}
]
},
{
name: "polygon 2",
points:[
{"x":5, "y":40},
{"x":23,"y":40},
{"x":23,"y":18},
{"x":5,"y":18},
{"x":5, "y":40}
]
},
{
name: "polygon 3",
points:[
{"x":-25, "y":40},
{"x":5,"y":40},
{"x":5,"y":34},
{"x":-25,"y":34},
{"x":-25, "y":40}
]
}]
Given the name of the polygon from the ‘polys’ object I need to find the color for that polygon from the ‘visitors’ object.
I’ve tried:
d = one object of the 'polys' obj
.attr("fill", function(d, visitors) {
for(var key in d){
if (key === 'name' && d.name === visitors.name){
return visitors.color;
}
}
});
I have no problem returning the color if it was in the ‘polys’ object which defines the polygon, but the ‘polys’ object will essentially be static and the ‘visitors’ object will be dynamic and the color will change based on the number of visitors. How do I return the color from the ‘visitors’ object?
Solution:
I actually got the answer from chatGPT:
// Select your polygons and set the fill color based on the 'visitors' data
d3.select("your-polygon-selector")
.attr("fill", function (d) {
const name = d.name; // Get the name of the current polygon
// Find the corresponding visitor object based on the polygon name
const visitor = visitors.find(visitor => visitor.name === name);
if (visitor) {
return visitor.color; // Set the fill color from the visitor object
} else {
// Handle the case where the visitor data is not found for the polygon
return "default-color"; // You can set a default color here
}
});
This worked.