简体   繁体   English

按关键字过滤数组

[英]Filter Array by keyword

I'm trying to write a search function for a data table, I have a collection of array objects and would prefer to search the whole object but right now I'm searching certain keys. 我正在尝试为数据表编写搜索功能,我有一个数组对象的集合,并且希望搜索整个对象,但是现在我正在搜索某些键。 The below code doesn't seem to work correctly. 以下代码似乎无法正常工作。

I have tried the following js: 我尝试了以下js:

searchResults() {

   if (!this.searchTable) this.fetch_bet_data();

   const searchableKeys = ["username", "bet_id"];

   this.bets = this.bets.filter(bet => {

      return searchableKeys.some(key => {

         return bet[key].toLowerCase().includes(this.searchTable);

      });

   });

},

So it works via the Bet_ID but the username. 因此它可以通过Bet_ID但可以使用用户名。 It gets keyword from a search box 它从搜索框中获取关键字

<input type="text" v-model="searchTable" class="form-control" placeholder="Search">
   <div class="input-group-btn">
      <button class="btn btn-success" @click="searchResults()" type="submit">
         <i class="glyphicon glyphicon-search"></i>
      </button>
   </div>

Ideal world I'd like to just search the whole object, but right now just having it work on what i have declared would be great 理想的世界,我只想搜索整个对象,但是现在让它在我声明的内容上起作用将是很棒的

Example of object: 对象示例:

bet_amount: "0.0000001" 
bet_id: "fe5f40-3ea93b" 
client_seed: "hash" 
created_at: 1547739644 
high: false 
multiplier: "2.00" 
nonce: 119
 profit: "-0.0000001" 
result: 
false roll: 80.82 
server_seed: "Seed is active needs to change server seed to reveal." server_seed_hash: "hash" 
threshold: 49.5 
user_id: "id" 
username: "graham"

One problem I can see with your approach. 我可以用您的方法看到一个问题。

You assign the filtered results to this.bets which means it will keep filtering on previous filters. 您将过滤后的结果分配给this.bets ,这意味着它将继续对先前的过滤器进行过滤。 You should assign the filtered result to a new variable. 您应该将过滤后的结果分配给新变量。

Here is a working example. 这是一个工作示例。

 let bets = [ { bet_amount: "0.0000001", bet_id: "fe5f40-3ea93b", client_seed: "hash", username: "graham" }, { bet_amount: "0.0000002", bet_id: "kjs93f-sflll0", client_seed: "hash", username: "roller" }, { bet_amount: "0.0000003", bet_id: "099s99-lpap11", client_seed: "hash", username: "card" } ] function searchResults() { //if (!this.searchTable) this.fetch_bet_data(); const searchableKeys = ["username", "bet_id"]; let results = bets.filter(bet => { return searchableKeys.some(key => { return bet[key].toLowerCase().includes(document.getElementById("theInput").value); }); }); console.log(results); } 
 <input id="theInput" type="text" v-model="searchTable" class="form-control" placeholder="Search"> <div class="input-group-btn"> <button class="btn btn-success" onClick="searchResults()" type="submit"> <i class="glyphicon glyphicon-search">Search</i> </button> </div> 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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