我正在使用以下代码从Firebase检索对象列表。我需要从列表中删除一个项目,但我的索引始终为-1。我在这里做什么错了?
filterItineraries(filters: any): any {
let num = 0;
this.allItineraries = [];
this.filteredItineraries = [];
for (let i = 0; i < 2; i++) {
if (i === 0) {
num = 0;
} else {
num = (filters.numberOfDays - 1);
}
const query = this.dataSvc.getAllItineraries()
.where('destination', '==', filters.destination)
.where('dateRange', 'array-contains', filters.dateRange[num]);
query.get()
.then(itineraryListSnapshot => {
this.allItineraries = [];
itineraryListSnapshot.forEach(snap => {
this.allItineraries.push({
id: snap.id,
jobCode: snap.data().jobCode,
destination: snap.data().destination,
startDate: snap.data().startDate,
endDate: snap.data().endDate,
workDetails: snap.data().workDetails,
userId: snap.data().userId
});
const index: number = this.allItineraries.indexOf(filters.id);
if (index !== -1) {
this.allItineraries.splice(index, 1);
}
console.log('index', index);
console.log('filters.id', filters.id);
console.log('filteredItineraries', this.allItineraries);
});
});
}
}
我也尝试过将它移到for循环之外,但是index = -1。
最后我尝试了:
this.filteredItineraries = this.allItineraries;
const index: number = this.filteredItineraries.indexOf(filters.id);
if (index !== -1) {
this.filteredItineraries.splice(index, 1);
}
console.log('index', index);
console.log('filters.id', filters.id);
console.log('filteredItineraries', this.filteredItineraries);
索引始终= -1
答案 0 :(得分:2)
此行没有执行您想要的操作:
const index: number = this.allItineraries.indexOf(filters.id);
index
在这里始终是-1
,因为allItineraries
是对象数组,而filters.id
是(从控制台输出的外观来看)字符串。 / p>
您需要自己遍历allItineraries
来找到条目e
在e.id === filters.id
处(您现有的比较是e === filters.id
)。
this.allItineraries = itineraryListSnapshot
.filter(snap => snap.id !== filters.id)
.map(snap => { id: snap.id, ...snap.data() });