Reputation: 3923
I have a D3 function where I want to return a specific data element based on a user selection.
For instance:
var selected = this.value;
line.y(function(d) { return d.selected; });
The selected
variable will be a placeholder for the real element name.
The above code block doesn't work, but I'm wondering if some other construct would work. I've tried several other combinations without luck including return d. + selected
.
The alternative that does work would be a case statement or many if/else statements such as:
if(selected === "element1") {
return d.element1;
}
else {
return d.element2;
}
I'd rather avoid this though since there are many different options.
Thanks for any help.
Upvotes: 1
Views: 819
Reputation: 13017
You can use this:
line.y(function(d) { return d[selected]; });
This has nothing to do with D3, it's JavaScript syntax:
d.element1
d['element1']
var key = 'element1';
d[key]
all access the same property.
Upvotes: 2