Searching on a variable-defined field with ElasticSearch

Here is the relevant code:

var field = String(querystring.parse(postData).field).toLowerCase();
var qryObj = {
"fields" : view_options,
"query":{
    "term" : { field : value} 
    }
};

The variable 'field' will be a string, like "number", "date", etc. What I want to do is search the index only in the field that is defined in the variable 'field'. This code works if I hardcode the string, like this:

"term" : { "number" : value} 

So can someone shed some light on a way to only search a specific field using a predefined variable instead of a string?

You can't use variables as keys in an Object literal. On the left of each :, identifiers themselves become the key's name rather than being evaluated as variables for their values.

console.log({ key: "value" });   // { key: 'value' }
console.log({ "key": "value" }); // { key: 'value' }

You'll have to build the Object first using bracket member operators, then apply it to the query object:

var term = {};
term[field] = value;

var qryObj = {
    fields: view_options,
    query: {
        term: term
    }
};

Update:

With ECMAScript 6, Object literals do now support computed keys using bracket notation for the key:

var qryObj = {
    fields: view_options,
    query: {
        term: {
            [field]: value
        }
    }
};