gpt4 book ai didi

javascript - JSON 搜索循环在第一次命中后停止

转载 作者:行者123 更新时间:2023-12-03 05:27:31 24 4
gpt4 key购买 nike

亲爱的 StackOverflow 社区,您好!我的问题似乎很简单,但我就是不明白我哪里做错了。

问题是,我有一个包含以下数据的 JSON:

var data = [{
"id": 0,
"friends": ["Mike", "John"],
"enemies": ["Albert", "Amy"],
"image": "https://link.com/1"
}, {
"id": 1,
"friends": ["Chad", "John"],
"enemies": ["Lawrence", "Amy"],
"image": "https://link.com/2"
}, {
"id": 2,
"friends": ["Craig", "John"],
"enemies": ["Adam", "Amy"],
"image": "https://link.com/3"
}, {
"id": 3,
"friends": ["Craig", "Bruce"],
"enemies": ["Adam", "Scott"],
"image": "https://link.com/4"
}];

现在我尝试使用用户的输入循环这些数据。例如,如果用户输入“Adam”,我想获取该对象的 id,可怜的 Adam 出现在敌人数组中。

到目前为止,我已经想出了以下代码:

function getObjectByEnemyName(name){
for (var i = 0; i < data.length; i++) { // In each object of the data array
for (var m = 0; m < data[i].enemies.length; m++) { // Locate the enemies array and search through each of its elements
if (data[i].enemies[m] == name) { // If the m'th element of the enemies array in the i'th object of the data array equals to the entered string
return data[i].id // Return the id value of the data array's i'th object
}
}
}
}


var found = getObjectByEnemyName("Adam");

例如,如果我搜索“Albert”,这完全没问题,因为他仅在 enemies 数组中出现一次。

但是当涉及到像“Adam”这样的查询时,我的函数在数据数组的第三个对象(id = 2)中找到第一个正确的命中,并拒绝继续,输出为 2,当下一个对象中实际上有另一个“Adam”时,我希望结果是这样的:

['2', '3']

为了实现这种类型的行为,我尝试在我正在使用的函数中插入更多的 forwhile 循环,但惨败。我还尝试使用一些第三方 Node 包来搜索我的数据数组,但也没有成功。

因此我的问题是:有没有办法告诉我的循环继续寻找其他匹配项,而不是在第一次正确命中时停止?任何帮助将不胜感激。

P.S.:我自己控制 JSON 数据的外观,因此如果问题隐藏在其组成方式中,我可以轻松更改它,请告诉我如何更改。

非常感谢您的关注!

最佳答案

实际上它在第一场比赛时停止,因为您正在返回第一场比赛......

如果您想要多个匹配项,可以将它们存储在一个数组中,并在搜索完成后返回整个数组:

function getObjectByEnemyName(name) {
var results = [];

for (var i = 0; i < data.length; i++) { // In each object of the data array
for (var m = 0; m < data[i].enemies.length; m++) { // Locate the enemies array and search through each of its elements
if (data[i].enemies[m] == name) { // If the m'th element of the enemies array in the i'th object of the data array equals to the entered string
results.push(data[i].id); // Return the id value of the data array's i'th object
}
}
}

return results;
}

顺便说一句,您可以按如下方式简化搜索:

function getObjectsByEnemyName(name) {
return data.filter(item => item.enemies.includes(name)).map(item => item.id);
}

关于javascript - JSON 搜索循环在第一次命中后停止,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41091790/

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