我有一个这样的线程对象数组
threadlist:Thread[]= [thread{id:1},thread{id:2},thread{id:3},...]
我在下面的用户对象中也有一个ThreadRelation数组,用于存储用户是否为某个线程添加了书签。
请注意,线程中的ID与数组中的ID不匹配。
user{
user_id:number,...(some other user typical properties)
threadRelations:ThreadRelation[]=[
threadRelation{
id:2,//relates to id property of a Thread object
isBookmarked:true
},
threadRelation{
id:18,
isBookmarked:true
},..
]}
我想创建一个仅返回带有用户书签线程的数组的函数。我可以使用两个for循环和if语句来实现此目的,但是我认为它不高效。
有一些方法可以直接在数组内找到该特定对象吗?
updateBookmarkedList(){
for (var i = 0; i < this.activeUser.threadsRelation.length; i++){
if ( this.activeUser.threadsRelation[i].bookmarked == true){
var searchId = this.activeUser.threadsRelation[i].id;
for (var j = 0; j < this.threadlist.length; j++){
if (this.threadlist[j].id == searchId){
this.userBookmarkedList.push(this.threadlist[j])
}
}
}
}
}
谢谢!
最佳答案
如果Thread.id
是唯一标识符,那么您实际上应该使用Map
而不是没有键的对象的Array
。没有键,您将不得不在没有其他选择的情况下迭代数组。
迭代Array
时,请尝试使用内置的迭代方法,例如forEach
。它们比循环更有效,看起来更整洁。
为了补充@Tamas-Hegedus's answer using ES6 iterator
feature,我使用当前版本的JavaScript创建了一个JSFiddle,以制作一个“ Array-Map”,如果Map
不是数字,则可以将其替换为Thread.id
。
请参见JSFiddle。