在做任何事情之前,我一直在检查这篇文章:How can I find matching values in two arrays? 但这对我没有帮助。我实在不明白。因此,如果我在这里解释我的问题,也许有人可以帮助我解决它。
我有一个学校项目(我应该根据用户的位置、标签、受欢迎程度等来匹配用户。 在对两个位置使用算法之前,我想要第一个非精确排序。所以基本上我想比较两个值,如“Paris”和“Paris”)
我的搜索函数返回一个 [],里面有两个 {},因此有两个人与我的第一个搜索值(性别)匹配
我正在使用 Node.js,我的数据库是 MySQL,我的函数到目前为止正在使用回调和 promise 。
所以这是我的第一个对象(它包含我的搜索者的信息)
[ RowDataPacket {
id: 34,
username: 'natedogg',
latitude: 48.8835,
longitude: 2.3219,
country: 'France',
city: 'Paris',
zipcode: 75017 } ]
这是第二个(包含 2 个用户)
[ RowDataPacket {
id: 33,
username: 'pablito',
latitude: 48.8921,
longitude: 2.31922,
country: 'France',
city: 'Paris',
zipcode: 75017 },
RowDataPacket {
id: 35,
username: 'tupac',
latitude: 48.8534,
longitude: 2.3488,
country: 'France',
city: 'levallois',
zipcode: 92300 } ]
不,我有这些数据,如何检查我的搜索者的位置是否 == 我的 otherUsersLocation(即使它们超过 1 个位置) 感谢您的帮助!
最佳答案
我为您编写了一些代码,该代码有效,您应该能够将其应用到您的情况。基本上,我们只是循环遍历我们想要搜索的对象并查看“city”属性。我重命名了一些变量以使发生的事情更加清晰。
var data = {
id: 34,
username: 'natedogg',
latitude: 48.8835,
longitude: 2.3219,
country: 'France',
city: 'Paris',
zipcode: 75017
};
var searchable = [{
id: 33,
username: 'pablito',
latitude: 48.8921,
longitude: 2.31922,
country: 'France',
city: 'Paris',
zipcode: 75017 },
{
id: 35,
username: 'tupac',
latitude: 48.8534,
longitude: 2.3488,
country: 'France',
city: 'levallois',
zipcode: 92300
}];
// this array is just to save obj when we have a match
var found =[];
// loop through each element in our searchable array
for(var i=0;i<searchable.length;++i){
if(data["city"] == searchable[i]["city"]){
// did we find it? push it onto the found array
console.log("found: " + searchable[i]["city"]);
found.push(searchable[i]["username"]);}
}
// look to see if we got what we wanted
console.log(found);
您可以按照相同的过程来匹配数据中的任何内容。
关于javascript - 匹配 JavaScript 数组中的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41571851/