反應

2017-04-09 55 views
0

在反應我有一個對象,它看起來像反應

{ 
{name: 'Colombia', code: 'CO'}, 
{name: 'Comoros', code: 'KM'}, 
{name: 'Congo', code: 'CG'}, 
...} 

我需要針對其用戶正在鍵入(我正在它從輸入字段)元件那裏搜索。由用戶編寫的每一個字母后,我需要把它與所有的名字比較,發現與部分

+2

這不是一個數組,它是一個嵌套對象。這也是無效的語法。 –

+0

是的你是對的 –

+0

那麼它是一個數組還是嵌套對象? – elmeister

回答

1

你想用filter()includes()

let a = [{ 
 
    name: 'Congo', 
 
    code: 'CG' 
 
    }, 
 
    { 
 
    name: 'France', 
 
    code: 'FR' 
 
    } 
 
]; 
 

 
document.getElementById('foo').addEventListener('keyup', e => { 
 
    let val = e.target.value.toLowerCase(); 
 
    let matches = a.filter(v => v.name.toLowerCase().includes(val)); 
 
    console.log(matches); 
 
});
<input id="foo">

+0

我已經得到輸出文本了。 state.value你可以修改代碼,我可以在課堂上使用它嗎? –

0

所有名稱假設你不小心用大括號{},而不是括號[]表示你的問題的數組,假設你可以使用ES6的功能,你可以使用Array.prototype.filter()String.prototype.includes()

// countries = your array 
// Assuming you put the user input in a state variable called this.state.search = the user input string 
var matchingCountries = countries.filter(element => element.name.includes(this.state.search)); 

如果你使用這個在組件的render功能,以及地方使所得matchingCountries陣列,該組件將反應性地更新爲this.state.search已更新。

0

我已經採取了糾正你的數據類型的自由:

data = [{name: 'Congo', code: 'CG'}, ...] 

,因爲您提供的版本將只拋出錯誤。

var data = [{name: 'Congo', code: 'CG'}]; 

... 

handleKeyPress = (event) => { 
    var value = this.event.target.value.toLowerCase(), 
     matches = data.filter(function (item) { 
      return item.name.substring(0, value.length).toLowerCase() === value; 
     }); 

    console.log(matches) 
} 
render: function(){ 
    return(
     <div> 
      <input type="text" onKeyPress={this.handleKeyPress} /> 
     </div> 
    ); 
} 

對不起,我的反應能力真的是分面值的,所以可能有更好的方式來訪問輸入的值,比event.target.value

+0

不幸使用您的代碼我得到一個錯誤,你可以看看代碼? https://github.com/ArmenSan/reactSearch 錯誤是 錯誤./js/app.js 模塊構建失敗:SyntaxError:意外的令牌(35:17) > 35 | handleKeyPress =(event)=> { |^ 36 | var value = this.event.target.value.toLowerCase(), 37 |匹配=數據。過濾器(函數(item)){return item.name.substring(0,value.length).toLowerCase()=== value; –

+0

爲什麼我們需要渲染函數? –

1

過濾基於搜索字符串的內容,像

var data = [{name: 'Comoros', code: 'KM'}, {name: 'Congo', code: 'CG'}, {name: 'Congo, The Democratic Republic of the', code: 'CD'}, {name: 'Cook Islands', code: 'CK'}, {name: 'Costa Rica', code: 'CR'}, {name: 'Cote D\'Ivoire', code: 'CI'}, {name: 'Croatia', code: 'HR'}, {name: 'Cuba', code: 'CU'}, {name: 'Cyprus', code: 'CY'}] 
 

 
var search = 'om'; 
 
var filterData = data.filter(item => item.name.includes(search)); 
 
console.log(filterData);