我有一个像这样的线程对象数组
threadlist:Thread[]= [thread{id:1},thread{id:2},thread{id:3},...]
我还在用户对象内有一个 ThreadRelation 数组,如下所示,用于存储用户是否为某个线程添加了书签。 请注意,Thread 中的 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”,如果 Thread.id
不是数字,您可以将其替换为 Map
。
参见JSFiddle .
关于javascript通过特定对象属性在对象数组中查找对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36451553/