试图循环JSON文件

时间:2017-02-07 10:43:06

标签: javascript json reactjs

我在React中创建了一个字典应用程序,我已经加载了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)
},

然而,我正在努力找到一种成功的循环方式来获得结果。控制台正在记录一个空数组。

任何人都可以建议我哪里出错吗?

1 个答案:

答案 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);
},