【发布时间】:2016-07-26 21:08:48
【问题描述】:
我有一个这样的线程对象数组
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])
}
}
}
}
}
谢谢!
【问题讨论】:
-
使用
Array.prototype.filter!附带说明,您的 JSON 无效,除非这是伪代码。在这种情况下,您应该提供您拥有的完整示例(使用有效数据)。 -
@Mr.Polywhirl 考虑将此作为答案。
标签: javascript arrays sorting typescript