gpt4 book ai didi

javascript - 在字典中搜索键并打印值 - Javascript

转载 作者:行者123 更新时间:2023-11-30 15:12:29 25 4
gpt4 key购买 nike

我有一本看起来有点像这样的字典:

var index = {
"Italian": [
{
"name": "Il Brigante",
"rating": "5.0"
},
{
"name": "Giardino Doro Ristorante",
"rating": "5.0"
}
],
"Mexican": [
{
"name": "Cosme",
"rating": "5.0"
}
]
}

我还有一个搜索栏,人们可以在其中输入查询。我想要做的是获取查询并在 index 中搜索它。

示例:search = "italian", results = {"name": "Il Brigante", "rating": "5.0"}, {"name": "Giardino Doro意大利餐厅", "rating": "5.0"}

这种搜索可能吗?任何帮助,将不胜感激。非常感谢。第四天快乐!

干杯,西奥

最佳答案

你可以试试看

var index = {
"Italian": [{
"name": "Il Brigante",
"rating": "5.0"
},
{
"name": "Giardino Doro Ristorante",
"rating": "5.0"
}
],
"Mexican": [{
"name": "Cosme",
"rating": "5.0"
}]
};

var search = "italian";


var results = Object.keys(index).reduce(function(a, b) {
if (b.toLowerCase() === search.toLowerCase()) {
return a.concat(index[b]);
}
return a;
}, []);

console.log(results);

可能是以后的要求!

如果你想要部分匹配,你只需要替换

if (b.toLowerCase() === search.toLowerCase()) {

if(b.toLowerCase().indexOf(search.toLowerCase()) !== -1) {

用于调整 - plunker

关于javascript - 在字典中搜索键并打印值 - Javascript,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44908809/

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