[英]Get Firebase unique ID from filtered object
我正在构建一个Angular应用程序,该应用程序通过500px API搜索地理位置并根据搜索结果返回照片。 如果有人多次搜索同一位置,则需要在API请求中增加对page=x
的搜索,以便返回新的结果。
我目前的处理方式是查询我在Firebase中的所有locations
,并使用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中location对象的父代。 data.locations
一个对象可能看起来像这样:
{ '-JUBNhmr_0kwSmHLw4FF' :
{ lat: 51.5073509, lng: -0.12775829999998223,
name: "London, UK", search_count: 1 }
}
而且findWhere()
函数可以找到它,但是它仅返回匹配的对象,而没有提供一种方法来提升树以获取父节点。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.