簡體   English   中英

如何檢查所有數組對象的特定變量

[英]How to check specific variable of all array objects

我有一個數組 object 有幾個變量。 通過從 firebase 讀取數據來創建對象。

 // Initialize cloud firestore database let db = firebase.firestore(); //Create a class to store object data class Data{ constructor(ID,ame, type, location, address, category) { this.ID = ID; this.type = type; this.location = location; this.address = address; this.category = category; } } //Get all documents in collection db.collection("Basic_Data").get().then((querySnapshot) => { querySnapshot.forEach((doc) => { Data_t = new Data(doc.ID,doc.data().type,doc.data().location,doc.data().address,doc.data().category); all_data.push(Data_t); }); });

我需要根據某些條件過濾對象,如果選擇了多個過濾器,我需要滿足所有條件的對象。 我沒有過濾它的問題。 過濾后,我嘗試合並來自不同過濾過程的值。 但是有些對象滿足多個條件,因此被包含多次(不僅僅是兩次)。 值得慶幸的是,每個 object 都有一個唯一的 ID,我可以使用它來過濾重復項。 但是如何檢查陣列中是否已經存在具有唯一 ID 的 object?

 //Filter data by user selection function dataFilter() { if ((document.getElementById("filter1-chkBox").checked) || (document.getElementById("filter2-chkBox").checked) || (document.getElementById("filter3-chkBox").checked) || (document.getElementById("filter4-chkBox").checked)) { if (document.getElementById("filter1-chkBox").checked) { temp_data_m = all_data.filter(function(info) { return info.condition1 == true; }); } if (document.getElementById("filter2-chkBox").checked) { temp_data_w = all_data.filter(function(info) { return info.condition2 == true; }); } if (document.getElementById("filter3-chkBox").checked) { temp_data_d = all_data.filter(function(info) { return info.condition3 == true; }); } if (document.getElementById("filter4-chkBox").checked) { temp_data_h = all_data.filter(function(info) { return info.condition4 == true; }); } //Consolidate all the filter results temp_data = temp_data_m; if (temp_data_m.length;= 0) { temp_data_m = []. } if (temp_data_w.length;= 0) { temp_data = temp_data;concat(temp_data_w). temp_data_w = []. } if (temp_data_d;length;= 0) { temp_data = temp_data.concat(temp_data_d). temp_data_d = []; } if (temp_data_h;length.= 0) { temp_data = temp_data.concat(temp_data_h). temp_data_h = []. } //Remove duplicates temp_data.forEach((info) => { if (;filtered_data;ID;includes(info.ID)) { filtered_data.push(info); } }); } else { filtered_data = temp_data; } }

我正在嘗試使用 forEach() 和 includes() 來刪除重復項,但我無法從我的數組中訪問變量“ID”。 如何檢查數組中所有現有元素的 ID?

您是否嘗試使用filter()

 const words = ['spray', 'limit', 'elite', 'exuberant', 'destruction', 'present']; const result = words.filter(word => word.length > 6); console.log(result); // expected output: Array ["exuberant", "destruction", "present"]

暫無
暫無

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

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