简体   繁体   中英

define field name in JavaScript object literal from variable

i need to change the field dynamically

   this.search = function(search, match) {
          var deferred = $q.defer()
          search({
            size: 10000,
            index: "products",
            body: {
              "query": {
                "match": {
                  [search]: {
                    "query": match,
                    // "operator": "and",
                    type:"phrase"
                  }
                }
              }
            }

but its showing the error 30:16 error Parsing error: Unexpected token [

You'll have to split it up so you can build the body object dynamically:

var body = {
    "query": {
        "match": { }
    }
};
body.query.match[search] = {
    "query": match,
    "type": "phrase"
};

This isn't an AngularJS problem - the problem is you are trying to use a Computed Property Name for the object literal when the browser you are using doesn't support it.

Computed Property Name documentation link:

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Object_initializer#Computed_property_names

To see the which browsers can & can't use Computed Property Names :

https://kangax.github.io/compat-table/es6/#test-object_literal_extensions_computed_properties

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM