javascript通过特定对象属性在对象数组中查找对象

标签 javascript arrays sorting typescript

我有一个像这样的线程对象数组

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/

相关文章:

javascript - 在警报框中显示信息并接受用户输入 - 标题、选择选项、确认、取消

javascript - 使用 jquery 禁用三星 S5 中的应用程序滚动

java - 这两个 Java 数组是否相同?

arrays - 快速排序字符串中的字符

algorithm - 最大嵌套区间集

javascript - : if((typeof OA ! = 'undefined' ) && OA ) 和 if(OA) 之间的区别

javascript - this.state.display && <h1>Displayed!</h1> 有效,但反之则不然?

arrays - fatal error : Cannot use string offset as an array

php - 数组中的导航/子导航结构

jquery - Javascript 按值对数组进行排序