gpt4 book ai didi

javascript - 尝试循环 JSON 文件

转载 作者:行者123 更新时间:2023-11-28 05:01:49 25 4
gpt4 key购买 nike

我正在 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)
},

但是,我正在努力寻找一种成功的方法来循环它以获得结果。控制台正在记录一个空数组。

有人可以建议我哪里出错了吗?

最佳答案

您可以通过添加比较函数来获得更好的匹配(在下面的示例中是 compareTerm 函数)。我所做的是比较术语是否以字典键开头,如果您希望它成为字符串的任何部分,您可以将其从 === 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);
},

关于javascript - 尝试循环 JSON 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42087730/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com