簡體   English   中英

從過濾的對象獲取Firebase唯一ID

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM