1

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.

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.