簡體   English   中英

Firestore 如何使用 javascript 檢查雲 Firestore 中的數組中是否存在元素

[英]Firestore how do I check if an element exists in an array in cloud firestore using javascript

我想檢查雲火庫中的數組中是否存在元素

這是一個示例元素(它是一個對象):

 var viewData = {ISBN: "8388838", ItemType: "Book", Shelf_Location: "YA FIC German xxx"}

這就是我所說的數組。 這是我正在談論的數組

這是我用來檢查此元素是否存在於雲 Firestore 中的數組中的代碼:

db.collection("users").doc("reservedItemsList").get().then((doc) => {
        if ((doc.data().reserved_items).includes(viewData)){
            alert("error")
        }
    }).catch((error) => {
        console.log("Error getting document:", error);
    });

上面的代碼不起作用,因為當我運行代碼console.log(typeof(doc.data().reserved_items))它返回了 object

如果您需要true / false的答案,您可以使用Array.prototype.some()通過 ISBN 進行查找,這應該是唯一標識符:

if((doc.data().reserved_items).some(({ISBN}) => ISBN === viewData.ISBN)){..

我認為您需要將viewData中的屬性與您的reserved_items中的對象進行比較。

不能使用includes()的原因是對象不相同(即使它們包含相同的信息。)

考慮以下示例

const a = {foo:'asd'};
const b = {foo:'123'};
const array1 = [a, b];

console.log(array1.includes({foo:'asd'})); // false
console.log(array1.includes(a)); // true

您可以使用find() function,或者如評論中所述, some() function。 下面,我使用了find() function:

const foundItem = reserved_items.find(item => {
 if(item.ISBN === viewData.ISBN){
  return item;
 }
});
if(foundItem) {
// viewData exists in reserved_items
}

以下是如何使用find() 函數

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

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