如何在 JS 中迭代哈希并返回所有匹配结果?

发布于 2024-11-10 13:16:50 字数 757 浏览 2 评论 0原文

我在一个函数中有以下一段 JS 代码,它响应用户按 Enter 键(未显示)。我关心的代码部分如下所示:

       $.each(cityhash,function(key,value){
            if(value['city']== user_input) {
                $('#city').empty().append(value['city']);
                $('#state').empty().append(value['city']);
            }

我有以下哈希:

cityhash =  [{"address":"07288 Albertha Station","city":"Littelside","state":"Missouri"},{"address":"0615 Mervin Rapid","city":"Tessmouth","state":"South Carolina"},{"address":"779 Elody Lock","city":"Littelside","state":"New Mexico"}]

如您所见,利特尔赛德市在哈希中出现了两次。我的问题是上面的 $.each 函数,只显示 2 个 Littlesides 中的 1 个。我想显示哈希中的所有匹配项,而不仅仅是 1 个匹配项。

如何更正我的代码以返回所有匹配的城市,而不是仅显示一个城市?

预先感谢您

I have the following piece of JS code within a function that responds to the user pressing enter (not displayed). The part of the code I am concerned with is shown:

       $.each(cityhash,function(key,value){
            if(value['city']== user_input) {
                $('#city').empty().append(value['city']);
                $('#state').empty().append(value['city']);
            }

I have the following hash:

cityhash =  [{"address":"07288 Albertha Station","city":"Littelside","state":"Missouri"},{"address":"0615 Mervin Rapid","city":"Tessmouth","state":"South Carolina"},{"address":"779 Elody Lock","city":"Littelside","state":"New Mexico"}]

As you can see, the city of Littelside appears twice in the hash. My problem is the above $.each function, only displays 1 of the 2 Littlesides. I would like to show all matches in the hash, not just 1 match.

How can I correct my code to return all matching cities rather than just showing one city?

Thank you in advance

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

娜些时光,永不杰束 2024-11-17 13:16:50

您需要摆脱empty() 调用。您将在每场比赛中清除#city/#state。

$('#city').append(value['city']);
$('#state').append(value['state']);

另外,您可能希望将州名称而不是城市名称附加到 #state 元素

You need to get rid of the empty() calls. You are clearing out #city/#state on each match.

$('#city').append(value['city']);
$('#state').append(value['state']);

Also, you probably want to append the state name and not the city name to the #state element

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文