2017-02-07 3 views
1

をループしようと、私はこのようになりますJSON辞書にロードされています:私が反応中に辞書アプリを作成していJSONファイル

{ 
"DIPLOBLASTIC": "Characterizing the ovum when it has two primary germinallayers.", 
"DEFIGURE": "To delineate. [Obs.]These two stones as they are here defigured. Weever.", 
"LOMBARD": "Of or pertaining to Lombardy, or the inhabitants of Lombardy.", 
"BAHAISM": "The religious tenets or practices of the Bahais.", 
"FUMERELL": "See Femerell." 
} 

ユーザーが入力フィールドに単語を入力し、値が次の関数に渡され、JSONで一致するキーが検索されます。一致する単語は、それぞれの値を持つ結果の配列にプッシュされます。

handleSearch: function(term) { 
    var term = term; 
    var results = []; 
    for (var key in Dictionary) { 
     if (Dictionary.hasOwnProperty(key)) { 
      if (term == Dictionary[key]) { 
      results.push(Dictionary[key]) 
      } 
     } 
    } 
    console.log(results) 
}, 

しかし、私は結果を得るためにそれをループするうまい方法を見つけるのに苦労しています。コンソールは空の配列を記録しています。

誰かが間違っている場所を教えてください。

+0

用語の価値は? –

答えて

0

比較機能を追加することで、よりよく一致させることができます(例の下ではcompareTermの機能です)。私が行ったことは、用語STARTSを辞書キーと比較すると、文字列の任意の部分にしたい場合は=== 0から> -1に変更することができます。

// compare function which needs to be added somewhere 
function compareTerm(term, compareTo) { 
    var shortenedCompareTo = compareTo 
    .split('') 
    .slice(0, term.length) 
    .join(''); 

    return term.indexOf(shortenedCompareTo.toLowerCase()) === 0; 
} 

// only changed the compare function 
handleSearch: function(term) { 
    var results = []; 
    for (var key in Dictionary) { 
     if (Dictionary.hasOwnProperty(key)) { 
      if (compareTerm(term, Dictionary[key])) { 
       results.push(Dictionary[key]) 
      } 
     } 
    } 

    console.log(results); 
}, 
関連する問題