0

My Javascript skills are fairly basic but advanced enough to get me to a position where I am able to design some relatively complex charts using the d3 library. I've now got to the point where I am looking to make some of my code reusable and this is where I've come across the first hurdle that the excellent api documentation can't get me past.

As an example, in the majority of my charts I want to add a legend. I have some basic code that adds a svg group for the legend which looks like this

var legend = chartContainer.selectAll(".legend")
  .data(d3.map(data, function(d){return d.FIELDNAME;}).keys())
  .enter().append("g")
  .attr("class", "legend")
  .attr("transform", function(d, i) { return "translate(0," + (((height/3)) + (i*20)) + ")"; });

what I'd like to be able to do is add a parameter to a function which allows me to set what field from the dataset is used in the legend. Something like the below... but that actually works :)

function addLegend(legendKey) {

var legend = chartContainer.selectAll(".legend")
  .data(d3.map(data, function(d){return d.legendKey;}).keys())
  .enter().append("g")
  .attr("class", "legend")
  .attr("transform", function(d, i) { return "translate(0," + (((height/3)) + (i*20)) + ")"; });
// rest of the legend code
}

called by

addLegend("FIELDNAME");

Lastly, understandably (perhaps) this didn't work either

function helper(legendKey){
  return legendKey;
}

function addLegend(helper) {

var legend = chartContainer.selectAll(".legend")
.data(d3.map(data, function test (d, addLegend){return d.addLegend;}).keys())
.enter().append("g")
.attr("class", "legend")
.attr("transform", function(d, i) { return "translate(0," + (((height/3)) + (i*20)) + ")"; });
 // rest of the legend code
}

addLegend(helper("agent"))

Any help would be greatly appreciated.

cb1210
  • 83
  • 5
  • 1
    You're looking for the `[ ]` operator. [See this question for example.](http://stackoverflow.com/questions/2349411/javascript-access-object-member-when-identifier-string-is-stored-in-a-var) There are many others if you search around. – Pointy Jul 13 '15 at 14:38
  • Perfect, thank you very much, and, now that I know the answer, I apologise for asking such a seemingly simple question. Unfortunately, as I didn't understand that an object was also a dictionary populated by its members, all my searches had been fruitless. Thanks again. – cb1210 Jul 13 '15 at 15:27
  • It's hard to search for that because, if you don't know the feature is there, you really don't know what you're looking for :) It's a common question here however and there are many answers covering different facets of the behavior. – Pointy Jul 13 '15 at 15:41
  • yes, now I know what I'm looking for, I've managed to find many interesting discussions around the topic that have extended my knowledge further. – cb1210 Jul 14 '15 at 14:54

0 Answers0