2017-02-07 120 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); 
},