我正在构建一个 Angular 应用程序,它通过 500px API 搜索地理位置并根据搜索结果返回照片。如果有人多次搜索同一位置,我需要在 API 请求上增加对 page=x
的搜索,以便返回新的结果。
我目前处理此问题的方法是查询 Firebase 中的所有位置
,并使用 Undescore.js _findWhere
功能对其进行过滤。如果位置名称与搜索词匹配,我会增加它,否则我会创建一个新的。
目前,我已经让它正常工作,以便在匹配时返回我的对象,但为了增加它,我需要 Firebase 分配给它的该对象的唯一 ID。
这是我的代码(从 CoffeeScript 转换而来;抱歉):
getSearchCount = function(result) {
var data;
// fetch the data from firebase as an object
data = $firebase(ref).$asObject();
return data.$loaded().then(function() {
var passed_data, plucked_result;
// search the object to see if a location matches the currently searched term
plucked_result = _.findWhere(data.locations, {
name: result.formattedAddress
});
// this is where I want to return the unique ID of the plucked result
return passed_data = [result, plucked_result];
});
};
saveLocation = function(passed_data) {
var plucked_result, result, search_count;
result = passed_data[0];
plucked_result = passed_data[1];
// if the search term doesn't exist, create a new one
if (plucked_result === null) {
search_count = 1;
return locationsRef.push({
name: result.formattedAddress,
lat: result.lat,
lng: result.lng,
search_count: search_count
});
} else {
// increment the search count on the query
// search_count = plucked_result.search_count + 1
// plucked_result.search_count = search_count
}
};
这是我为 console.log(data) 返回的对象:
d {$$conf: Object, $id: null, $priority: null, foo: "bar", locations: Object…}
$$conf: Object
$id: null
$priority: null
locations: Object
-JUBNhmr_0kwSmHLw4FF: Object
lat: 51.5073509
lng: -0.12775829999998223
name: "London, UK"
search_count: 1
__proto__: Object
-JUBQREGJpQnXxiMIaKm: Object
lat: 48.856614
lng: 2.3522219000000177
name: "Paris, France"
search_count: 1
__proto__: Object
__proto__: Object
photos: Object
__proto__: Object
这是我从 console.log(plucked_result) 返回的对象:
Object {lat: 51.5073509, lng: -0.12775829999998223, name: "London, UK", search_count: 1}
总而言之,我需要 Firebase 唯一 ID (-JUBNhmr_0kwSmHLw4FF)。
或者也许我正在以一种完全复杂的方式来做这件事,但可以简化?我基本上需要做的就是创建一种对 API 请求进行分页的方法,这样我就不会两次提取同一页面的结果。
最佳答案
简短回答:
您可以用如下循环替换 underscore.js findWhere()
调用:
var key;
var location;
for(key in data.locations) {
location = data.locations[key];
if(location.name == result.formattedAddress) {
break;
}
}
这将产生存储在 location
中的您感兴趣的对象,其名称存储在 key
中。
为什么会出现这种情况
您要查找的唯一 ID(Firebase 文档将其称为对象名称)是 Firebase 中位置对象的父级。 data.locations
中的一个对象可能如下所示:
{ '-JUBNhmr_0kwSmHLw4FF' :
{ lat: 51.5073509, lng: -0.12775829999998223,
name: "London, UK", search_count: 1 }
}
而findWhere()
函数可以定位到它,但它只返回匹配到的对象,并没有提供向上一棵树获取父节点的方法。
关于javascript - 从过滤的对象中获取 Firebase 唯一 ID,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25275948/