1

I'm trying to filter some JSON data, but I would like the lookup to be based on selection of a drop down. However, I just can't get the syntax correct when trying to do this. Currently the following works in my code, great:

var as = $(json).filter(function (i, n) {
    return (n.FIELD1 === "Yes"
});

However, what I would like to do is replace the FIELD1 value with a var from the drop down. Something like this following, which is not working:

var dropdownResult = "FIELD1";
var as = $(json).filter(function(i, n) {
    return (n.dropdownResult === "Yes"
});

I'm trying to get the var to become the field name after the n. but it's not working.

Thanks for your time. Sorry if this has been answered many times before and is obvious to you.

Rory McCrossan
  • 331,213
  • 40
  • 305
  • 339
D. Nichols
  • 13
  • 3
  • What is `$(json)` supposed to do? The argument to `$()` should be either a selector or HTML, not JSON. That should be `JSON.parse(json)`. – Barmar Oct 07 '16 at 15:33

1 Answers1

0

To use a variable value as the key of an object you should use bracket notation, like this:

var dropdownResult = "FIELD1";
var as = $(json).filter(function(i, n) {
    return n[dropdownResult] === "Yes";
});

I removed the extraneous ( you left in your code - I presume this was just a typo as it would have created a syntax error and stopped your code from working at all.

Also note that it's much better practice to use a boolean value over a string 'Yes'/'No'

Rory McCrossan
  • 331,213
  • 40
  • 305
  • 339
  • Thank you very much. I was't sure about the different way to pass it, but this works exactly as I wanted it to. – D. Nichols Oct 10 '16 at 15:30