在“活动搜索”字段名称中转义冒号

时间:2018-05-29 00:09:04

标签: javascript reactjs elasticsearch reactive reactivesearch

我正在测试一个非常基本的reactive search实现。

我的代码如下:     从'react'导入React,{Component};     从'@ appbaseio / reactivesearch'导入{ReactiveBase,DataSearch,ResultCard};     从'./logo.svg'导入徽标;     import'./App.css';

class App extends Component {
  render() {
    return (
      <div className="App">
        <header className="App-header">
          <img src={logo} className="App-logo" alt="logo" />
          <h1 className="App-title">Welcome to React</h1>
        </header>

        <ReactiveBase
            app="indexName"
            url="https://someurl.amazonaws.com"
          >

          <DataSearch
            componentId="SearchSensor"
            dataField={ "field_product:title" }
            autoSuggest={true}
          />    

          <ResultCard
             componentId="results"
             dataField="field_product"
             react={{
               "and": ["SearchSensor"]
             }}
             onData={(res)=>({
               "image": res.image,
               "title": res.field_product:title,
               "description":   res.description
             })}
           />

          </ReactiveBase>
      </div>
    );
  }

}

export default App;

我在索引中的字段看起来有点如下:

{
  "_index": "kirana11",
  "_type": "product_autocomplete",
  "_id": "66641",
  "_version": 1,
  "_score": 1,
  "_source": {
    "id": 66641,
    "description": "Some Nestle Product ",
    "field_product:title": "Nestle Product",    
    "field_product:commerce_price:amount": 83
}

在上面的示例中,当我调用像res.image这样的字段时,它可以完美地运行。但是,field_product:title&amp;等字段field_product:commerce_price:amount会返回错误,如下所示:

  

语法错误:意外的令牌,预期,(34:41)

访问带冒号的字段的正确方法是什么?有没有办法逃脱它?

1 个答案:

答案 0 :(得分:1)

将其包裹在引号周围并使用括号代替点表示法来访问该属性:

res['field_product:title']

这也是您使用变量访问属性的方式:

const key = 'field_product:title';
res[key]

虽然改变你的json结构可能会更好:

fieldProduct: {
  title: '',
  commercePrice: ...
}
相关问题